12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package middleware
- import (
- "encoding/json"
- "github.com/gin-gonic/gin"
- "github.com/product-definition/utils/base"
- "math"
- "time"
- "github.com/sirupsen/logrus"
- )
- func Logger() gin.HandlerFunc {
- return func(ctx *gin.Context) {
- start := time.Now()
- ctx.Next()
- if base.GetNoLogFlag(ctx) == true {
- return
- }
- stop := time.Since(start)
- latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
- dataLength := ctx.Writer.Size()
- if dataLength < 0 {
- dataLength = 0
- }
- _ = ctx.Request.ParseForm()
- requestBody := ctx.Request.PostForm.Encode()
- if len(requestBody) > 10240 {
- requestBody = "too big not show"
- }
- render, exist := ctx.Get("render")
- var retCode int
- if exist == true {
- retCode = render.(base.TRenderJson).ReturnCode
- } else {
- retCode = 0
- }
- response, _ := json.Marshal(render)
- if len(string(response)) > 10240 {
- response = []byte("too big not show")
- }
- logrus.NewEntry(logrus.StandardLogger()).WithFields(logrus.Fields{
- "requestId": base.GetRequestId(ctx),
- "handle": ctx.HandlerName(),
- "type": "http",
- "retCode": retCode,
- "latency": latency, // time to process
- "requestBody": requestBody,
- "requestPath": ctx.Request.URL.RequestURI(),
- "httpCode": ctx.Writer.Status(),
- "clientIp": ctx.ClientIP(),
- "method": ctx.Request.Method,
- "referer": ctx.Request.Referer(),
- "dataLength": dataLength,
- "userAgent": ctx.Request.UserAgent(),
- }).Info(string(response))
- }
- }
- func LoggerBeforeRun(ctx *gin.Context) {
- customCtx := ctx.CustomContext
- logrus.NewEntry(logrus.StandardLogger()).WithFields(logrus.Fields{
- "requestId": base.GetRequestId(ctx),
- "handle": customCtx.HandlerName(),
- "type": customCtx.Type,
- }).Info("start")
- }
- func LoggerAfterRun(ctx *gin.Context) {
- customCtx := ctx.CustomContext
- stop := customCtx.EndTime.Sub(customCtx.StartTime)
- latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
- retCode := 0
- if customCtx.Error != nil {
- retCode = -1
- base.StackLogger(ctx, customCtx.Error)
- }
- logrus.NewEntry(logrus.StandardLogger()).WithFields(logrus.Fields{
- "requestId": base.GetRequestId(ctx),
- "handle": customCtx.HandlerName(),
- "type": customCtx.Type,
- "retCode": retCode,
- "latency": latency,
- }).Info("end")
- }
|