hugapi / hug

Embrace the APIs of the future. Hug aims to make developing APIs as simple as possible, but no simpler.
MIT License
6.86k stars 388 forks source link

How to prevent GET requests logging only? #919

Open eduardopezzi opened 5 months ago

eduardopezzi commented 5 months ago
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?

Sahithiaele commented 5 months ago

can i please be assigned to this issue ?

eduardopezzi commented 5 months ago

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())
Sahithiaele commented 5 months ago

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.