Log the request and response bodies for certain endpoints/handlers #2640
Replies: 1 comment
-
|
The issue is that You have to be careful with the request body specifically: once it's read, it's exhausted, so you must "reset" it using Here is a clean way to set this up: // 1. Middleware to capture bodies
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if c.Request().Body != nil {
reqBody, _ := io.ReadAll(c.Request().Body)
c.Request().Body = io.NopCloser(bytes.NewBuffer(reqBody))
c.Set("capturedReqBody", string(reqBody))
}
return next(c)
}
})
// 2. Configure RequestLogger
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogURI: true,
LogStatus: true,
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
reqBody, _ := c.Get("capturedReqBody").(string)
logger.Info().
Str("uri", v.URI).
Int("status", v.Status).
Str("body", reqBody).
Msg("request")
return nil
},
}))For response bodies, you would use a similar pattern but you'd need a custom wrapper for |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! I am using Zerolog with the RequestLoggerWithConfig middleware, and I want to append to the same log the request and response bodies for certain handlers. I have tried using the provided BodyDump middleware but couldn't get it to append to the same log json produced by zerolog. Is there a way to do this?
This is the logging middleware:
Beta Was this translation helpful? Give feedback.
All reactions