fastapi loguru日志管理

fastapi loguru日志管理
  • 与传统的logging相比,不需要复杂的配置过程,打印的日志更加优雅(彩色的)

  • hans.py

    import logging
    from types import FrameType
    from typing import cast
    
    from loguru import logger
    
    
    class InterceptHandler(logging.Handler):
        def emit(self, record: logging.LogRecord) -> None:  # pragma: no cover
            # Get corresponding Loguru level if it exists
            try:
                level = logger.level(record.levelname).name
            except ValueError:
                level = str(record.levelno)
    
            # Find caller from where originated the logged message
            frame, depth = logging.currentframe(), 2
            while frame.f_code.co_filename == logging.__file__:  # noqa: WPS609
                frame = cast(FrameType, frame.f_back)
                depth += 1
    
            logger.opt(depth=depth, exception=record.exc_info).log(
                level, record.getMessage(),
            )
    
  • settings.py

    from hands import InterceptHandler
    
    LOGGING_LEVEL = logging.DEBUG if DEBUG else logging.INFO
    LOGGERS = ("uvicorn.asgi", "uvicorn.access")
    
    logging.getLogger().handlers = [InterceptHandler()]
    for logger_name in LOGGERS:
        logging_logger = logging.getLogger(logger_name)
        logging_logger.handlers = [InterceptHandler(level=LOGGING_LEVEL)]
    
    log_file_path = os.path.join(BASE_DIR, 'logs/wise.log')
    err_log_file_path = os.path.join(BASE_DIR, 'logs/wise.err.log')
    
    loguru_config = {
        "handlers": [
            {"sink": sys.stderr, "level": "INFO",
             "format": "<green>{time:YYYY-mm-dd HH:mm:ss.SSS}</green> | {thread.name} | <level>{level}</level> | "
                       "<cyan>{module}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"},
            {"sink": log_file_path, "rotation": "500 MB", "encoding": 'utf-8'},
            {"sink": err_log_file_path, "serialize": True, "level": 'ERROR', "rotation": "500 MB",
             "encoding": 'utf-8'},
        ],
    }
    logger.configure(**loguru_config)
    
  • info级别日志输出到wise.log, error级别输出到wise.err.log

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值