2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FastAPIのUvicornログをLoguruで統一する方法

Posted at

背景

FastAPIプロジェクトにLoguru導入したが、Uvicornのログが標準のまま。
UvicornのログもLoguruのログ形式に寄せたい。

INFO:     Started server process [50656]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
2024-05-10 23:11:23.479 | ERROR    | backend.interface.api.v1.messages:create_user_message:22 - Failed to create user message
INFO:     127.0.0.1:61688 - "POST /v1/messages HTTP/1.1" 500 Internal Server Error

やったこと

  1. UvicornログをLoguruの形式に変換

    import logging
    from loguru import logger
    
    
    class InterceptHandler(logging.Handler):
        def emit(self, record):
            # 既存のログレコードの属性を使用してLoguruでログを出力
            logger_opt = logger.opt(depth=6, exception=record.exc_info)
            logger_opt.log(record.levelname, record.getMessage())
    
    
    def setup_logger():
        # uvicornログをInterceptHandlerにリダイレクト
        for _logger in ("uvicorn", "uvicorn.error", "uvicorn.access"):
            logging_logger = logging.getLogger(_logger)
            logging_logger.handlers = [InterceptHandler()]
            logging_logger.propagate = False  # ログが2重出力されるのを防止
    

  2. あとはmainで呼び出すだけ

    from fastapi import FastAPI
    from backend.logging.config import setup_logger
    
    setup_logger()
    app = FastAPI()
    

結果

Loguruのログに切り替わったことを確認

2024-05-10 23:22:41.864 | INFO     | uvicorn.server:_serve:82 - Started server process [50805]
2024-05-10 23:22:41.864 | INFO     | uvicorn.lifespan.on:startup:48 - Waiting for application startup.
2024-05-10 23:22:41.865 | INFO     | uvicorn.lifespan.on:startup:62 - Application startup complete.
2024-05-10 23:24:26.892 | ERROR    | backend.interface.api.v1.messages:create_user_message:22 - Failed to create user message
2024-05-10 23:24:26.892 | INFO     | uvicorn.protocols.http.httptools_impl:send:481 - 127.0.0.1:61785 - "POST /v1/messages HTTP/1.1" 500
2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?