hug icon indicating copy to clipboard operation
hug copied to clipboard

How to prevent GET requests logging only?

Open eduardopezzi opened this issue 1 year ago • 3 comments

import hug
from threading import Thread
from src.libs.versionMiddleware import VersionMiddleware

api = hug.API(__name__)
api.http.add_middleware(
    hug.middleware.CORSMiddleware(api, allow_origins=["*"])
)
api.http.add_middleware(
    VersionMiddleware('prometheus-version')
)

Implementing HUG API I am trying to prevent the GET requests output at the container logs/prompt

I tried to make a custom middleware without success... any suggestion?

eduardopezzi avatar Feb 12 '24 16:02 eduardopezzi

can i please be assigned to this issue ?

Sahithiaele avatar Feb 15 '24 18:02 Sahithiaele

sure, I tried this code, but get requests still trashing my container's log

class SilentGetLoggingMiddleware(hug.middleware.LoggingMiddleware):
    def log(self, request, response=None):
        if request.method != 'GET':
            super().log(request, response)

api = hug.API(__name__)
api.http.add_middleware(CORSMiddleware(api, allow_origins=["*"]))
api.http.add_middleware(SilentGetLoggingMiddleware())

eduardopezzi avatar Feb 16 '24 00:02 eduardopezzi

it seems there's an issue with the hug.middleware.LoggingMiddleware not being silent for GET requests. To work around this, you can use the standard Python logging module directly to configure logging and filter out GET requests.

`import hug from hug.middleware import CORSMiddleware import logging from src.libs.versionMiddleware import VersionMiddleware

class SilentGetLoggingMiddleware: def process_request(self, request, response): if request.method == 'GET': return None
return True
api = hug.API(name) api.http.add_middleware(CORSMiddleware(api, allow_origins=["*"])) api.http.add_middleware(SilentGetLoggingMiddleware()) api.http.add_middleware(VersionMiddleware('prometheus-version'))

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

@hug.get('/') def hello(): return "Hello, World!" `

In this example, I've created a SilentGetLoggingMiddleware class that implements the process_request method. This method checks if the request method is GET and returns None to skip the logging for GET requests. Otherwise, it returns True to allow the request to be processed and logged.

Additionally, the logging module is configured directly using basicConfig to set the logging level and format.

Sahithiaele avatar Feb 16 '24 16:02 Sahithiaele