背景
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
やったこと
-
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重出力されるのを防止
-
あとは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