[DEV] cc.addApiCallNoticeLog

This commit is contained in:
bryan 2025-04-24 15:44:44 +08:00
parent 98eac47127
commit b3b2a1c13b
2 changed files with 37 additions and 26 deletions

7
api.go
View File

@ -117,13 +117,12 @@ func middlewareMyApiEngine() gin.HandlerFunc {
defer log.Cleanup()
// Step 2. init *api.Context
req := c.Request
log.DebugfWithDepth(1, "[%s|%s|%s]", req.Method, req.Host, req.RequestURI)
cc := New(c)
c.Set("cc", cc)
cc.Set("cc", cc)
defer cc.addApiCallNoticeLog()()
// Step 3. do request
c.Next()
cc.Next()
// Step 4. recorde metrics
cc.recordMetrics()

View File

@ -27,7 +27,8 @@ type Context struct {
resultentry string
httpstatus int
starttime time.Time
output interface{}
output interface{} // case 1: for user get real errcode; case 2: for notice log
noticedepth int
errcode int
}
@ -130,10 +131,7 @@ func (c *Context) RESULT(output interface{}) error {
}
var t = reflect.TypeOf(output)
defer func(o *interface{}) {
b, err := json.Marshal(o)
if err != nil {
return
}
calldepth := 0
switch c.resultentry {
case "RESULT":
@ -143,19 +141,8 @@ func (c *Context) RESULT(output interface{}) error {
case "RESULT_PARAMETER_ERROR":
calldepth = 2
}
//// cut log if too long ////// begin //////////////
if len(b) > 1024 {
//no := retag.Convert(*o, retag.NewView("json", "!logignore"))
//if nb, err := json.Marshal(no); err != nil {
// return
//} else {
// b = nb
//}
}
//// cut log if too long ////// end ////////////////
cost := time.Now().Sub(c.starttime).Milliseconds()
noticeStr := fmt.Sprintf("cost: %dms, output: '%s'", cost, string(b))
log.NoticefWithDepth(calldepth, noticeStr)
c.output = o
c.noticedepth = calldepth
}(&output)
if _, ok := t.FieldByName("ErrCode"); !ok {
@ -203,6 +190,14 @@ func (c *Context) ApiHandler() Handler {
return ApiHandler(c.Context)
}
func (c *Context) ApiHandlerWithNoNil() Handler {
h := c.ApiHandler()
if h == nil {
h = unimplementHandler{c.Context}
}
return h
}
func (c *Context) shapeOutput(o interface{}) {
if c.output == nil {
return
@ -219,15 +214,32 @@ func (c *Context) shapeOutput(o interface{}) {
return
}
func (c *Context) addApiCallNoticeLog() func() {
h, req := c.ApiHandlerWithNoNil(), c.Request
log.DebugfWithDepth(1, "[>>>>>>:%s,%s,%s]", h.ApiName(), req.Method, req.RequestURI)
return func() {
var (
o = c.output
b, err = json.Marshal(o)
costus = time.Now().Sub(c.starttime).Microseconds()
costms = float64(costus) / 1000.0
)
if err != nil {
b = []byte(fmt.Sprintf("marshal output error:%s", err))
}
if len(b) > 1024 { // cut log if too long
b = append(b[0:1000], b[len(b)-24:]...)
}
log.Noticef("[<<<<<<:%s,code:%d,cost:%dms] output: '%s", h.ApiName(), c.errcode, int64(costms), string(b))
}
}
func (c *Context) recordMetrics() {
if metricApiCounter == nil ||
metricApiSummary == nil {
return
}
var h = c.ApiHandler()
if h == nil {
h = unimplementHandler{c.Context}
}
var h = c.ApiHandlerWithNoNil()
var (
api = h.ApiName()
appid = c.AppId