Home  >  Article  >  Backend Development  >  How to Log Response Body in Gin Middleware?

How to Log Response Body in Gin Middleware?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 09:14:02143browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn