修改日志机制

This commit is contained in:
Tian jianyong 2025-12-26 17:09:21 +08:00
parent 353a4efd66
commit 70c4641472
3 changed files with 36 additions and 14 deletions

2
.gitignore vendored
View File

@ -48,7 +48,6 @@ coverage.xml
# Django stuff:
*.log
*.log.*
local_settings.py
db.sqlite3
db.sqlite3-journal
@ -116,5 +115,6 @@ dmypy.json
*.swo
# Project specific
logs/
face_recognition.log
output.mp4

View File

@ -58,8 +58,8 @@ role_mapping:
# 日志配置
logging:
level: "DEBUG" # DEBUG, INFO, WARNING, ERROR
file: "face_recognition.log"
level: "INFO" # DEBUG, INFO, WARNING, ERROR
dir: "logs" # 日志目录
max_bytes: 10485760 # 10MB
backup_count: 5

View File

@ -810,29 +810,51 @@ class FaceRecognitionSystem:
def _setup_logging(self):
"""设置日志系统"""
log_config = self.config['logging']
log_dir = log_config.get('dir', 'logs')
# 确保日志目录存在
os.makedirs(log_dir, exist_ok=True)
# 按日期生成日志文件名
date_str = datetime.now().strftime('%Y%m%d')
log_file = os.path.join(log_dir, f'face_rec_{date_str}.log')
self.logger = logging.getLogger('FaceRecognition')
self.logger.setLevel(getattr(logging, log_config['level']))
self.logger.setLevel(getattr(logging, log_config.get('level', 'INFO')))
# 文件处理器
# 清理旧日志保留最近的5个
self._cleanup_old_logs(log_dir)
# 只保留文件处理器
file_handler = RotatingFileHandler(
log_config['file'],
maxBytes=log_config['max_bytes'],
backupCount=log_config['backup_count']
log_file,
maxBytes=log_config.get('max_bytes', 10 * 1024 * 1024),
backupCount=log_config.get('backup_count', 5)
)
# 控制台处理器
console_handler = logging.StreamHandler()
# 格式化
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
'%(asctime)s - %(levelname)s - %(message)s'
)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
self.logger.addHandler(console_handler)
self.logger.info(f"日志文件: {log_file}")
def _cleanup_old_logs(self, log_dir: str, keep_days: int = 7):
"""清理旧的日志文件保留最近N天"""
try:
from datetime import datetime, timedelta
cutoff_date = (datetime.now() - timedelta(days=keep_days)).strftime('%Y%m%d')
for f in os.listdir(log_dir):
if f.startswith('face_rec_') and f.endswith('.log'):
date_part = f.replace('face_rec_', '').replace('.log', '')
if date_part < cutoff_date:
os.remove(os.path.join(log_dir, f))
except Exception:
pass
def _get_chinese_font(self) -> str:
"""获取中文字体路径"""