Intention/api/logger_util.py

35 lines
1.1 KiB
Python
Raw 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.

import logging
from logging.handlers import RotatingFileHandler
import os
LOG_DIR = "logs"
LOG_FILE = "app.log"
LOG_PATH = os.path.join(LOG_DIR, LOG_FILE)
MAX_BYTES = 5 * 1024 * 1024 # 5MB
BACKUP_COUNT = 5
# 全局共用的 handler只初始化一次
_handler = None
def setup_logger(name: str, level=logging.INFO) -> logging.Logger:
global _handler
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
logger = logging.getLogger(name)
logger.setLevel(level) # 设置这个 logger 的最低级别
# 避免重复添加 handler只添加一次
if not _handler:
_handler = RotatingFileHandler(LOG_PATH, maxBytes=MAX_BYTES, backupCount=BACKUP_COUNT, encoding='utf-8')
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(name)s] %(message)s')
_handler.setFormatter(formatter)
_handler.setLevel(logging.DEBUG) # Handler 设置最低等级,捕获所有内容
if not logger.handlers:
logger.addHandler(_handler)
logger.propagate = False # 避免日志冒泡打印两遍
return logger