gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
76.96k stars 7.92k forks source link

Access gin context in gin logger middleware #2759

Open roumanite opened 3 years ago

roumanite commented 3 years ago
    router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
        ctx := param.Request.Context()
        // Same format as default gin.Logger(), with TraceID injected into the logs
        span, _ := tracer.SpanFromContext(param.Request.Context())
        fmt.Println(ctx)
        spew.Dump(param.ErrorMessage)
        return fmt.Sprintf("[GIN] %v | %3d | %13vms | %15s | %-7s %#v | %v | \n%s",
            param.TimeStamp.Format("2006/01/02 - 15:04:05"),
            param.StatusCode,
            float64(param.Latency)/float64(time.Millisecond),
            param.ClientIP,
            param.Method,
            param.Path,
            span.Context().TraceID(),
            param.ErrorMessage,
        )
    }))

Is there anyway to get the gin context of the request? I want to access c.Errors() directly, not converted to ErrorMessage... Thanks

appleboy commented 3 years ago

@roumanite maybe you can try the logger middleware: https://github.com/gin-contrib/logger