Open laggu opened 2 weeks ago
@appleboy It makes two separate logs. What I wanted to do is adding some more data in gin.Context to one unified log
@laggu What is your scenario?
This is example code for my scenario
// usage for developer
r.GET("/test", logger.SetLogger(
logger.WithContext(func(c *gin.Context, l *zerolog.Event) *zerolog.Event {
return l.Any("test", c.MustGet("test"))
}),
), func(c *gin.Context) {
c.Set("test", rand.Intn(100))
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})
// add function to config
type EventFn func(*gin.Context, *zerolog.Event) *zerolog.Event
func WithContext(fn func(*gin.Context, *zerolog.Event) *zerolog.Event) Option {
return optionFunc(func(c *config) {
c.context = fn
})
}
// add more information from context before logging
if cfg.context != nil {
evt = cfg.context(c, evt)
}
evt.
Int("status", c.Writer.Status()).
Str("method", c.Request.Method).
Str("path", path).
Str("ip", c.ClientIP()).
Dur("latency", latency).
Str("user_agent", c.Request.UserAgent()).
Int("body_size", c.Writer.Size()).
Msg(msg)
gin-zap also support this feature https://github.com/gin-contrib/zap/blob/b95a398fd4ef395af6b684b9e5b474371990841c/zap.go#L38
@appleboy how do you think??
@laggu I will take it.
is there any way to log values in gin.Context after my gin handler finish?
I set some values to gin.Context and tried to log them with request log However, as middleware is called before my gin handler, I don't have any values in gin.Context in logger middleware.
I think it would be better if logger middleware get one more function which called after user handler so that, developer can log more useful information.