Henry
发布于 2026-01-06 / 4 阅读
0
0

Python - Sample - pers_logging.py

背景简介

在 Python 项目中,统一的日志配置对于应用的监控和调试至关重要。下面介绍一个简洁实用的日志配置方案。

前置信息

详细信息

核心功能

这个日志配置模块 (app/core/logging.py) 提供了以下特性:

  • 集中配置:通过 setup_logging() 函数统一设置日志级别和格式
  • 灵活配置:支持从配置文件读取或参数传入日志设置
  • 避免重复:自动检测防止重复添加处理器
  • 即插即用:可在 FastAPI、Celery 等组件中直接调用

Logging 代码

# app/core/pers_logging.py
"""Centralized logging configuration for the application.

This module provides a `setup_logging` function to configure the root logger
with a consistent format and level. It can be imported and called at the
start of any application component (e.g., FastAPI, Celery worker) to ensure
uniform logging.

The module can also be executed directly to test the logging configuration.
"""

import logging
import sys
from typing import Optional

from app.core import settings


def setup_logging(
    level: Optional[str] = None,
    format_string: Optional[str] = None,
) -> None:
    """Configures the root logger for the application.

    This function sets up the basic configuration for the logging module,
    including the log level, format, and the handler. It is designed to be
    called once at the application's startup.

    Args:
        level: The logging level (e.g., "INFO", "DEBUG"). If None, it will
            be read from the application's settings.
        format_string: The log message format string. If None, it will be
            read from the application's settings.
    """
    # Determine the effective log level
    log_level = (level or settings.LOG_LEVEL).upper()
    log_format = format_string or settings.LOG_FORMAT

    # Create a formatter
    formatter = logging.Formatter(log_format)

    # Create a stream handler (writes to sys.stderr by default)
    stream_handler = logging.StreamHandler(sys.stderr)
    stream_handler.setFormatter(formatter)

    # Configure the root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(log_level)
    
    # Avoid adding multiple handlers if setup_logging is called multiple times
    if not root_logger.handlers:
        root_logger.addHandler(stream_handler)

    logging.info(
        "Logging configured with level '%s' and format '%s'.",
        log_level,
        log_format,
    )


if __name__ == "__main__":
    """Standalone execution for testing the logging configuration.

    When this script is run directly, it configures the logger and emits
    messages at various levels to demonstrate the output.
    """
    print("--- Testing Logging Configuration ---")
    setup_logging()  # Use default settings from config.py

    # Get a logger for this module
    logger = logging.getLogger(__name__)

    # Log messages at different severity levels
    logger.debug("This is a DEBUG message.")
    logger.info("This is an INFO message.")
    logger.warning("This is a WARNING message.")
    logger.error("This is an ERROR message.")
    logger.critical("This is a CRITICAL message.")
    print("--- Test Complete ---")

使用方法

  • 在应用启动时调用
from app.core.logging import setup_logging

setup_logging()  # 使用默认配置
# 或自定义配置
setup_logging(level="DEBUG", format_string="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
  • 获取并使用日志记录器
import logging

logger = logging.getLogger(__name__)
logger.info("应用启动完成")

优势特点

  • 简洁高效:单一函数完成所有配置
  • 可维护性强:集中管理,易于修改
  • 生产就绪:考虑了多次调用的边界情况
  • 易于测试:支持独立运行验证配置

这个日志配置方案适合大多数 Python 项目,能够快速建立起统一的日志记录机制。


以上便是本文的全部内容,感谢您的阅读,如遇到任何问题,欢迎在评论区留言讨论。



评论