Home > Article > Backend Development > How to Log Response Body in Gin Middleware?
Logging Response Body in Gin Middleware
In Gin, logging the response body in a middleware requires intercepting and storing the response before it is written. Here's how to achieve this:
Create a custom writer that intercepts Write() calls and stores the body:
import bytes class bodyLogWriter(gin.ResponseWriter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.body = bytes.Buffer() def Write(self, data): self.body.write(data) return super().Write(data)
Implement a middleware function that uses the custom writer to intercept the response:
from functools import wraps def gin_body_log_middleware(func): @wraps(func) def inner(context, *args, **kwargs): context.writer = bodyLogWriter(context.writer) wrapped_func(context, *args, **kwargs) status_code = context.writer.status_code if status_code >= 400: # Access the logged response body print("Response body:", context.writer.body.getvalue().decode()) return inner
Register the middleware in your Gin router:
router.Use(gin_body_log_middleware)
This middleware intercepts all responses and logs the body for requests with a status code of 400 or higher. For static file requests, a more sophisticated wrapper that wraps the Gin engine is necessary.
The above is the detailed content of How to Log Response Body in Gin Middleware?. For more information, please follow other related articles on the PHP Chinese website!