QAUP_Management/tools/logging_config.py
2025-10-16 18:33:44 +08:00

55 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import os
from logging.handlers import RotatingFileHandler
def setup_logger(name, log_file, level=logging.INFO, max_bytes=10*1024*1024, backup_count=5):
"""
配置日志记录器
Args:
name: 日志记录器名称
log_file: 日志文件路径
level: 日志级别
max_bytes: 单个日志文件最大字节数默认10MB
backup_count: 保留的备份日志文件数量
Returns:
logging.Logger: 配置好的日志记录器
"""
# 创建logs目录如果不存在
log_dir = os.path.dirname(log_file)
if log_dir and not os.path.exists(log_dir):
os.makedirs(log_dir)
# 创建日志记录器
logger = logging.getLogger(name)
logger.setLevel(level)
# 避免重复添加处理器
if not logger.handlers:
# 创建文件处理器(带滚动)
file_handler = RotatingFileHandler(
log_file,
maxBytes=max_bytes,
backupCount=backup_count,
encoding='utf-8'
)
# 创建控制台处理器
console_handler = logging.StreamHandler()
# 设置格式
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# 添加处理器到记录器
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger