Files
douyin_guaji-main/douyin_logging.py
T
Your Name 47e6b016c5 refactor: Remove deprecated files and enhance configuration settings
- Deleted outdated markdown files and scripts related to previous implementations.
- Updated `config.json` to adjust thresholds and settings for 福袋 detection and reservation handling.
- Improved logging and error handling across various modules for better monitoring and user experience.
- Introduced a new screenshot management module to facilitate real-time operation and success tracking.
- Enhanced GUI elements to support new configuration options and improve usability.
2025-12-20 20:11:28 +08:00

337 lines
11 KiB
Python

"""
日志系统配置与工具模块
====================
功能:
1. 标准 logging 配置(支持日志轮转、级别管理)
2. 增强的日志记录工具(自动记录调用者信息、异常堆栈等)
3. 性能监控装饰器(记录函数调用耗时)
4. 上下文管理器(记录代码块执行时间)
"""
from __future__ import annotations
import os
import sys
import time
import logging
import logging.handlers
import traceback
import inspect
from datetime import datetime
from typing import Optional, Callable, Any, Dict
from functools import wraps
import path_config
# 全局日志配置
_logging_configured = False
_logger_cache: Dict[str, logging.Logger] = {}
def get_logger(name: str = None) -> logging.Logger:
"""获取指定名称的 logger,如果未配置则自动配置"""
if not _logging_configured:
configure_logging()
if name is None:
# 自动获取调用者模块名
try:
frame = inspect.currentframe()
if frame and frame.f_back:
caller_frame = frame.f_back
name = caller_frame.f_globals.get('__name__', 'root')
else:
name = 'root'
except Exception:
name = 'root'
finally:
if 'frame' in locals():
del frame
if name not in _logger_cache:
_logger_cache[name] = logging.getLogger(name)
return _logger_cache[name]
def configure_logging(
log_level: str = None,
log_file: str = None,
max_bytes: int = 10 * 1024 * 1024, # 10MB
backup_count: int = 5,
enable_console: bool = True,
enable_file: bool = True,
) -> None:
"""配置日志系统
参数:
log_level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL),默认从 config.json 读取
log_file: 日志文件路径,默认使用 logs/unified.log
max_bytes: 单个日志文件最大大小(字节),超过后轮转
backup_count: 保留的备份文件数量
enable_console: 是否输出到控制台
enable_file: 是否输出到文件
"""
global _logging_configured
# 从 config.json 读取配置
if log_level is None or log_file is None:
try:
import json
config_path = path_config.get_config_path()
if os.path.exists(config_path):
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
if log_level is None:
log_level = config.get('log_level', 'INFO')
if log_file is None:
log_file = config.get('log_unified_path', 'logs/unified.log')
except Exception:
if log_level is None:
log_level = 'INFO'
if log_file is None:
log_file = 'logs/unified.log'
# 规范化日志级别
numeric_level = getattr(logging, log_level.upper(), logging.INFO)
# 确保日志目录存在
if enable_file:
log_dir = os.path.dirname(log_file)
if log_dir and not os.path.isabs(log_file):
log_file = os.path.join(path_config.PROJECT_ROOT, log_file)
log_dir = os.path.dirname(log_file)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
# 配置根 logger
root_logger = logging.getLogger()
root_logger.setLevel(numeric_level)
# 清除已有的 handlers(避免重复配置)
root_logger.handlers.clear()
# 日志格式:时间戳 - [级别] - 模块名:函数名:行号 - 消息
detailed_format = (
'%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s'
)
simple_format = '%(asctime)s - [%(levelname)s] - %(message)s'
# 控制台输出
if enable_console:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(numeric_level)
console_formatter = logging.Formatter(
simple_format,
datefmt='%Y-%m-%d %H:%M:%S'
)
console_handler.setFormatter(console_formatter)
root_logger.addHandler(console_handler)
# 文件输出(带轮转)
if enable_file:
try:
# 使用 RotatingFileHandler 实现日志轮转
file_handler = logging.handlers.RotatingFileHandler(
log_file,
maxBytes=max_bytes,
backupCount=backup_count,
encoding='utf-8-sig', # 使用 BOM 避免 Windows 乱码
errors='replace'
)
file_handler.setLevel(numeric_level)
file_formatter = logging.Formatter(
detailed_format,
datefmt='%Y-%m-%d %H:%M:%S.%f'
)
file_formatter.default_msec_format = '%s.%03d' # 毫秒精度
file_handler.setFormatter(file_formatter)
root_logger.addHandler(file_handler)
except Exception as e:
# 文件 handler 创建失败,只输出到控制台
try:
print(f"[日志配置] 警告:无法创建日志文件 {log_file}: {e}")
except Exception:
pass
_logging_configured = True
def log_function_call(
logger: Optional[logging.Logger] = None,
log_args: bool = True,
log_result: bool = False,
log_time: bool = True,
min_duration: float = 0.0, # 只记录超过此耗时的调用
):
"""装饰器:记录函数调用信息(参数、返回值、耗时)
参数:
logger: 使用的 logger,默认自动获取
log_args: 是否记录函数参数
log_result: 是否记录返回值
log_time: 是否记录执行时间
min_duration: 最小耗时阈值(秒),低于此值不记录耗时
"""
def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
if logger is None:
_logger = get_logger()
else:
_logger = logger
func_name = func.__name__
start_time = time.time()
# 记录函数调用
if log_args:
args_str = ', '.join([str(arg)[:100] for arg in args[:3]]) # 只记录前3个参数,避免过长
kwargs_str = ', '.join([f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]])
call_info = f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
if len(args) > 3 or len(kwargs) > 3:
call_info += "..."
_logger.debug(f"调用函数: {call_info}")
# 执行函数
try:
result = func(*args, **kwargs)
elapsed = time.time() - start_time
# 记录执行结果
if log_time and elapsed >= min_duration:
_logger.debug(f"函数 {func_name} 执行完成,耗时: {elapsed:.3f}秒")
if log_result:
result_str = str(result)[:200] # 限制长度
_logger.debug(f"函数 {func_name} 返回值: {result_str}")
return result
except Exception as e:
elapsed = time.time() - start_time
_logger.exception(
f"函数 {func_name} 执行异常,耗时: {elapsed:.3f}秒",
exc_info=True
)
raise
return wrapper
return decorator
class LogContext:
"""上下文管理器:记录代码块执行时间"""
def __init__(
self,
message: str,
logger: Optional[logging.Logger] = None,
level: str = "DEBUG",
log_on_exit: bool = True,
):
self.message = message
self.logger = logger or get_logger()
self.level = getattr(logging, level.upper(), logging.DEBUG)
self.log_on_exit = log_on_exit
self.start_time = None
def __enter__(self):
self.start_time = time.time()
self.logger.log(self.level, f"{self.message} [开始]")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.log_on_exit:
return False
elapsed = time.time() - self.start_time
if exc_type is None:
self.logger.log(
self.level,
f"{self.message} [完成] 耗时: {elapsed:.3f}秒"
)
else:
self.logger.log(
logging.ERROR,
f"{self.message} [异常] 耗时: {elapsed:.3f}秒",
exc_info=(exc_type, exc_val, exc_tb)
)
return False # 不抑制异常
def get_caller_info(skip_frames: int = 0) -> Dict[str, Any]:
"""获取调用者信息(模块名、函数名、行号)
参数:
skip_frames: 跳过的栈帧数(用于在装饰器中获取真正的调用者)
返回:
包含 module, function, line, file 的字典
"""
try:
frame = inspect.currentframe()
if frame:
# 跳过当前函数和装饰器
for _ in range(skip_frames + 2):
if frame.f_back:
frame = frame.f_back
else:
break
if frame:
return {
'module': os.path.basename(frame.f_code.co_filename),
'function': frame.f_code.co_name,
'line': frame.f_lineno,
'file': frame.f_code.co_filename,
}
except Exception:
pass
finally:
if 'frame' in locals():
del frame
return {
'module': 'unknown',
'function': 'unknown',
'line': 0,
'file': 'unknown',
}
def format_exception_info(exc_info=None) -> str:
"""格式化异常信息为字符串
参数:
exc_info: 异常信息元组 (type, value, traceback),默认使用 sys.exc_info()
返回:
格式化的异常堆栈字符串
"""
if exc_info is None:
exc_info = sys.exc_info()
if exc_info[0] is None:
return ""
try:
return ''.join(traceback.format_exception(*exc_info))
except Exception:
return f"异常: {exc_info[1]}"
# 自动配置日志(在模块导入时)
if not _logging_configured:
# 延迟配置,避免在导入时读取 config.json 失败
try:
configure_logging()
except Exception:
pass