Last active
May 22, 2025 19:14
-
-
Save somespecialone/012481fa1efa8f4133742ab4470db247 to your computer and use it in GitHub Desktop.
Setup logging function with Loguru. Suitable for Uvicorn+FastAPI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://pawamoy.github.io/posts/unify-logging-for-a-gunicorn-uvicorn-app/ | |
| import sys | |
| import logging | |
| from typing import Sequence | |
| from loguru import logger | |
| LOG_FORMAT = "{time:YYYY-MM-DD HH:mm:ss} <lvl>| {level: ^6} |</> {message}" | |
| class InterceptHandler(logging.Handler): | |
| def emit(self, record): | |
| # get corresponding Loguru level if it exists | |
| try: | |
| level = logger.level(record.levelname).name | |
| except ValueError: | |
| level = record.levelno | |
| # find caller from where originated the logged message | |
| frame, depth = logging.currentframe(), 2 | |
| while frame.f_code.co_filename == logging.__file__: | |
| frame = frame.f_back | |
| depth += 1 | |
| logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage()) | |
| def setup_logging( | |
| log_level: int | str = logging.INFO, | |
| muted_loggers: Sequence[str] = (), | |
| muted_level: int | str = logging.ERROR, | |
| log_format=LOG_FORMAT, | |
| ): | |
| # intercept everything at the root logger | |
| logging.root.handlers = [InterceptHandler()] | |
| logging.root.setLevel(log_level) | |
| # prevent log pollution | |
| for logger_name in muted_loggers: | |
| logging.getLogger(logger_name).setLevel(muted_level) | |
| # remove every other logger's handlers and propagate to root logger | |
| for name in logging.root.manager.loggerDict.keys(): | |
| other_logger = logging.getLogger(name) | |
| other_logger.handlers = [] | |
| other_logger.propagate = True | |
| # configure loguru | |
| logger.level("INFO", color="<m>") | |
| logger.configure(handlers=({"sink": sys.stdout, "colorize": True, "format": log_format},)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment