How to Log Response Body in Gin Middleware?

Susan Sarandon
Release: 2024-11-09 09:14:02
Original
167 people have browsed it

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)
Copy after login

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
Copy after login

Register the middleware in your Gin router:

router.Use(gin_body_log_middleware)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template