Python 项目 Logging 实践案例

定义BaseLoggerbase_logger.py

# -*- coding: utf-8 -*-

import sys
import logging
import logging.handlers
from typing import Union

from cfg.common import PROJ_ROOT, PROJ_NAME


LOG_DIR = PROJ_ROOT.joinpath('logs')
LOG_FMTR = logging.Formatter('%(processName)10s:%(threadName)10s - %(asctime)s [%(levelname)-8s] '
                             '[%(name)-20s - %(filename)s:%(lineno)d %(funcName)20s()]: '
                             '%(message)s')
LOG_DEFAULT_FILENAME = 'general.log'

_LOG_DEFAULT_FILE_MAXBYTES = 50_000_000
_LOG_DEFAULT_FILE_BACKUPCNT = 5


def get_console_handler(level: Union[str, int]) -> logging.StreamHandler:
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(level)
    ch.setFormatter(LOG_FMTR)

    return ch


def get_rotate_file_handler(level: Union[str, int],
                            filename: str = LOG_DEFAULT_FILENAME) -> logging.handlers.RotatingFileHandler:
    filepath = LOG_DIR.joinpath(filename)
    rfh = logging.handlers.RotatingFileHandler(filepath, encoding='utf-8',
                                               maxBytes=_LOG_DEFAULT_FILE_MAXBYTES,
                                               backupCount=_LOG_DEFAULT_FILE_BACKUPCNT)
    rfh.setLevel(level)
    rfh.setFormatter(LOG_FMTR)

    return rfh


def _create_base_logger():
    logger = logging.getLogger(PROJ_NAME)
    logger.setLevel(logging.CRITICAL)

    ch = get_console_handler(logging.CRITICAL)
    rfh = get_rotate_file_handler(logging.WARN)

    logger.addHandler(rfh)
    logger.addHandler(ch)

    return logger


base_logger = _create_base_logger()

使用base_logger派生模块级Logger:

from logger.logger import base_logger, get_console_handler


def _create_xxx_logger():
    logger = base_logger.getChild(__name__)
    logger.setLevel('DEBUG')

    if not logger.handlers:
        ch = get_console_handler('DEBUG')
        logger.addHandler(ch)
        fh = get_rotate_file_handler('INFO', f'{__name__}.log')
        logger.addHandler(fh)
    return logger


_logger = _create_xxx_logger()
posted @ 2023-05-08 17:15  LexLuc  阅读(40)  评论(0编辑  收藏  举报