Loguru python dynamically update the log format with each request to a FastAPI app

84 Views Asked by At

I want to intergrate loguru into my FastAPI app in the middleware, so that I can monitor and troubleshoot every request that comes in.

One thing I want to achieve, that I don't see a clear solution to, is dynamically set the log format string with every request that comes in. For example:

LOG_LEVEL = 'DEBUG'
logger.remove(0)
log_format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>"
logger.add(sys.stdout, level=LOG_LEVEL, format=log_format, colorize=True, backtrace=True, diagnose=True)
logger.add('log.log', rotation='2 MB', level=LOG_LEVEL, format=log_format, colorize=False, backtrace=True, diagnose=True)

@app.middleware("http")
async def process_middleware(request: Request, call_next):
    # in here, I want the log_format string to include the request.url
    # so that I can just call
    logger.debug(request)
    # and it will include the URL in the log format itself
    # is this possible?
1

There are 1 best solutions below

0
Rahul Agarwal On

You have to use logger.contextualize to pass the exact URL

  1. update the log format to accept request_url
log_format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <green>{extra[request_url]}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>"

logger.configure(extra={"request_url": None})  # Default values

logger.add(sys.stdout, level=LOG_LEVEL, format=log_format, colorize=True, backtrace=True, diagnose=True)

logger.add('log.log', rotation='2 MB', level=LOG_LEVEL, format=log_format, colorize=False, backtrace=True, diagnose=True)
  1. then in middleware, use logger.contextualize
@app.middleware("http")
async def process_middleware(request: Request, call_next):
    with logger.contextualize(request_url=request.url.path):
        response = await call_next(request)
        return response

Anytime during the API call, whenever you use logger, the request URL will be added automatically.