Files
RemoveWeeklyShapshot/utils/logger.py
2026-02-22 11:19:31 +08:00

39 lines
1.3 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 os, logging
from datetime import datetime
def get_logger():
"""配置日志系统返回logger实例"""
# 创建logger
logger = logging.getLogger('vm_snapshot_cleanup')
logger.setLevel(logging.INFO)
# 避免重复添加处理器
if logger.handlers:
return logger
# 定义日志格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 获取项目根目录
LOG_DIR = os.path.join(BASE_DIR, 'logs') # 获取日志文件根目录
os.makedirs(LOG_DIR, exist_ok=True) # 自动创建目录
log_file = os.path.join(LOG_DIR, f'{datetime.now().strftime("%Y-%m-%d")}-removeweeklysnapshot.log') # 日志文件路径
# 文件处理器(写入日志文件)
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setFormatter(formatter) # 应用格式化器
# 控制台处理器(输出到终端)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
# 添加处理器
logger.addHandler(file_handler)
logger.addHandler(console_handler)
logger.setLevel(logging.DEBUG) # 默认只会记录Info以上级别的日志
return logger
# 全局logger实例
logger = get_logger()