Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
laggu opened this issue Nov 7, 2024 · 6 comments
Open

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

laggu opened this issue Nov 7, 2024 · 6 comments

Comments

@laggu
Copy link

laggu commented Nov 7, 2024

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
Copy link
Member

appleboy commented Nov 8, 2024

See #76

@appleboy appleboy closed this as completed Nov 8, 2024
@laggu
Copy link
Author

laggu commented Nov 9, 2024

@appleboy It makes two separate logs. What I wanted to do is adding some more data in gin.Context to one unified log

@appleboy
Copy link
Member

appleboy commented Nov 9, 2024

@laggu What is your scenario?

@appleboy appleboy reopened this Nov 9, 2024
@laggu
Copy link
Author

laggu commented Nov 11, 2024

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
Copy link
Author

laggu commented Nov 14, 2024

@appleboy how do you think??

@appleboy
Copy link
Member

@laggu I will take it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants