github.com/zooyer/miskit@v1.0.71/micro/middleware.go (about) 1 package micro 2 3 import ( 4 "fmt" 5 "net/http" 6 "runtime/debug" 7 "time" 8 9 "github.com/gin-gonic/gin" 10 "github.com/zooyer/miskit/errors" 11 "github.com/zooyer/miskit/log" 12 "github.com/zooyer/miskit/trace" 13 ) 14 15 func Logger(logger *log.Logger) gin.HandlerFunc { 16 return func(ctx *gin.Context) { 17 start := time.Now() 18 path := ctx.Request.URL.Path 19 query := ctx.Request.URL.RawQuery 20 21 ctx.Next() 22 23 code := ctx.Writer.Status() 24 latency := time.Since(start) 25 26 output := logger.Error 27 switch { 28 case code >= http.StatusOK && code < http.StatusMultipleChoices: 29 output = logger.Info 30 case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: 31 output = logger.Info 32 case code >= http.StatusBadRequest && code < http.StatusInternalServerError: 33 output = logger.Warning 34 default: 35 output = logger.Error 36 } 37 38 if t := trace.Get(ctx); t != nil { 39 if t.TraceID != "" { 40 logger.Tag(false, "trace_id", t.TraceID) 41 } 42 if t.SpanID != "" { 43 logger.Tag(false, "span_id", t.SpanID) 44 } 45 if t.Tag != "" { 46 logger.Tag(false, "tag", t.Tag) 47 } 48 if t.Lang != "" { 49 logger.Tag(false, "lang", t.Lang) 50 } 51 if len(t.Content) > 0 { 52 logger.Tag(false, "content", string(t.Content)) 53 } 54 } 55 56 logger.Tag( 57 false, 58 "ip", ctx.ClientIP(), 59 "method", ctx.Request.Method, 60 "path", path, 61 "query", query, 62 "code", code, 63 "latency", latency, 64 ) 65 66 // TODO response 67 68 output(ctx) 69 } 70 } 71 72 func Recover(logger *log.Logger) gin.HandlerFunc { 73 return func(ctx *gin.Context) { 74 defer func() { 75 if e := recover(); e != nil { 76 logger.Tag(false, "panic", e).Error(ctx, string(debug.Stack())) 77 errors.New(errors.ServicePanic, fmt.Errorf("%v", e)).Metric() 78 ctx.AbortWithStatusJSON(http.StatusInternalServerError, e) 79 } 80 }() 81 ctx.Next() 82 } 83 } 84 85 func Trace(callee string) gin.HandlerFunc { 86 return func(ctx *gin.Context) { 87 trace.Set(ctx, trace.New(ctx.Request, callee)) 88 } 89 }