Loguru python 通过对 FastAPI 应用程序的每个请求动态更新日志格式

问题描述 投票:0回答:1

我想将 loguru 集成到中间件中的 FastAPI 应用程序中,以便我可以监控传入的每个请求并对其进行故障排除。

我想要实现的一件事是,我没有看到明确的解决方案,即为每个传入的请求动态设置日志格式字符串。例如:

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?
python python-3.x logging fastapi loguru
1个回答
0
投票

您必须使用 logger.contextualize 来传递确切的 URL

  1. 更新日志格式以接受
    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. 然后在中间件中,使用 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
© www.soinside.com 2019 - 2024. All rights reserved.