gin-contrib / logger

Gin middleware/handler to logger url path using rs/zerolog
MIT License
192 stars 35 forks source link

logging value in gin.Context after gin handler finish #95

Open laggu opened 2 weeks ago

laggu commented 2 weeks ago

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.

appleboy commented 2 weeks ago

See https://github.com/gin-contrib/logger/pull/76

laggu commented 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

appleboy commented 2 weeks ago

@laggu What is your scenario?

laggu commented 2 weeks ago

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

laggu commented 1 week ago

@appleboy how do you think??

appleboy commented 21 hours ago

@laggu I will take it.