diff --git a/douyin/logging/douyin_logging.py b/douyin/logging/douyin_logging.py index a1de7b0..be47264 100644 --- a/douyin/logging/douyin_logging.py +++ b/douyin/logging/douyin_logging.py @@ -38,7 +38,7 @@ _logging_configured = False _logger_cache: Dict[str, logging.Logger] = {} # 日志监控器实例 -_log_monitor: Optional['LogRotationMonitor'] = None +_log_monitor: Optional["LogRotationMonitor"] = None class RotatingDatedFileHandler(logging.FileHandler): @@ -79,6 +79,7 @@ class RotatingDatedFileHandler(logging.FileHandler): self.max_bytes = max_bytes self.backup_count = backup_count self.compress_old = compress_old + self.per_run = per_run self.current_date = datetime.now().strftime(date_format) self.current_filename = self._get_filename_for_date(self.current_date) @@ -125,7 +126,10 @@ class RotatingDatedFileHandler(logging.FileHandler): # 如果序号0的文件已满,查找可用的序号 for sequence in range(1, self.backup_count + 1): filename = self._get_filename_for_date(date_str, sequence) - if not os.path.exists(filename) or os.path.getsize(filename) < self.max_bytes: + if ( + not os.path.exists(filename) + or os.path.getsize(filename) < self.max_bytes + ): return filename # 如果所有序号都满了,返回最后一个(会触发覆盖最旧的) @@ -139,7 +143,10 @@ class RotatingDatedFileHandler(logging.FileHandler): new_filename = self._get_next_filename(date_str) # 如果文件已存在且已满,删除最旧的文件 - if os.path.exists(new_filename) and os.path.getsize(new_filename) >= self.max_bytes: + if ( + os.path.exists(new_filename) + and os.path.getsize(new_filename) >= self.max_bytes + ): try: os.remove(new_filename) except Exception: @@ -157,7 +164,7 @@ class RotatingDatedFileHandler(logging.FileHandler): self._check_date_rotation() # 检查是否需要大小轮转 - if self.stream and hasattr(self.stream, 'tell'): + if self.stream and hasattr(self.stream, "tell"): try: current_size = self.stream.tell() if current_size >= self.max_bytes: @@ -172,8 +179,8 @@ class RotatingDatedFileHandler(logging.FileHandler): # 每100条记录或每1秒检查一次日期 self._date_check_counter += 1 should_check_date = ( - self._date_check_counter >= 100 or - (datetime.now() - self._last_date_check_time).total_seconds() >= 1.0 + self._date_check_counter >= 100 + or (datetime.now() - self._last_date_check_time).total_seconds() >= 1.0 ) if should_check_date: @@ -241,15 +248,15 @@ def compress_log_file(log_file: str) -> bool: if file_size < 1024 * 1024: # 小于1MB不压缩 return False - compressed_file = log_file + '.gz' + compressed_file = log_file + ".gz" # 如果压缩文件已存在,跳过 if os.path.exists(compressed_file): return False # 压缩文件 - with open(log_file, 'rb') as f_in: - with gzip.open(compressed_file, 'wb', compresslevel=9) as f_out: + with open(log_file, "rb") as f_in: + with gzip.open(compressed_file, "wb", compresslevel=9) as f_out: shutil.copyfileobj(f_in, f_out) # 验证压缩文件 @@ -259,9 +266,11 @@ def compress_log_file(log_file: str) -> bool: # 删除原文件 os.remove(log_file) try: - print(f"[日志压缩] 压缩完成: {os.path.basename(log_file)} " - f"({file_size/1024:.1f}KB -> {compressed_size/1024:.1f}KB, " - f"压缩率: {compressed_size/file_size*100:.1f}%)") + print( + f"[日志压缩] 压缩完成: {os.path.basename(log_file)} " + f"({file_size/1024:.1f}KB -> {compressed_size/1024:.1f}KB, " + f"压缩率: {compressed_size/file_size*100:.1f}%)" + ) except Exception: pass return True @@ -281,7 +290,7 @@ def cleanup_old_logs( keep_days: int = 30, max_total_size_gb: float = 10.0, # 最大总大小(GB) compress_after_days: int = 7, # 几天后压缩 - compress: bool = True + compress: bool = True, ) -> Dict[str, int]: """智能清理旧日志文件:支持时间、大小、压缩三重策略 @@ -297,10 +306,10 @@ def cleanup_old_logs( 清理统计信息 """ stats = { - 'deleted': 0, - 'compressed': 0, - 'total_size_mb': 0.0, - 'freed_space_mb': 0.0, + "deleted": 0, + "compressed": 0, + "total_size_mb": 0.0, + "freed_space_mb": 0.0, } try: @@ -321,17 +330,17 @@ def cleanup_old_logs( return stats # 按修改时间排序(最新的在前) - all_files.sort(key=lambda x: os.path.getmtime(x), reverse=True) + all_files.sort(key=os.path.getmtime, reverse=True) # 计算总大小 total_size = sum(os.path.getsize(f) for f in all_files if os.path.exists(f)) - stats['total_size_mb'] = total_size / 1024 / 1024 + stats["total_size_mb"] = total_size / 1024 / 1024 # 如果总大小超过限制,先删除最旧的文件 max_total_size_bytes = max_total_size_gb * 1024 * 1024 * 1024 if total_size > max_total_size_bytes: # 按时间排序,删除最旧的 - sorted_files = sorted(all_files, key=lambda x: os.path.getmtime(x)) + sorted_files = sorted(all_files, key=os.path.getmtime) for log_file in sorted_files: if total_size <= max_total_size_bytes: @@ -341,8 +350,8 @@ def cleanup_old_logs( file_size = os.path.getsize(log_file) os.remove(log_file) total_size -= file_size - stats['deleted'] += 1 - stats['freed_space_mb'] += file_size / 1024 / 1024 + stats["deleted"] += 1 + stats["freed_space_mb"] += file_size / 1024 / 1024 except Exception as e: try: print(f"[日志清理] 删除文件失败 {log_file}: {e}") @@ -361,11 +370,11 @@ def cleanup_old_logs( # 从文件名提取日期 filename = os.path.basename(log_file) # 处理压缩文件扩展名 - if filename.endswith('.gz'): + if filename.endswith(".gz"): filename = filename[:-3] # 提取日期部分 - date_part = filename.replace(f"{base_name}_", "").split('.')[0] + date_part = filename.replace(f"{base_name}_", "").split(".")[0] try: file_date = datetime.strptime(date_part, "%Y-%m-%d") @@ -376,13 +385,17 @@ def cleanup_old_logs( if file_date < cutoff_date: file_size = os.path.getsize(log_file) os.remove(log_file) - stats['deleted'] += 1 - stats['freed_space_mb'] += file_size / 1024 / 1024 + stats["deleted"] += 1 + stats["freed_space_mb"] += file_size / 1024 / 1024 # 如果超过压缩天数且未压缩,压缩 - elif compress and file_date < compress_date and not log_file.endswith('.gz'): + elif ( + compress + and file_date < compress_date + and not log_file.endswith(".gz") + ): if compress_log_file(log_file): - stats['compressed'] += 1 + stats["compressed"] += 1 except Exception as e: try: @@ -391,10 +404,12 @@ def cleanup_old_logs( pass # 输出统计信息 - if stats['deleted'] > 0 or stats['compressed'] > 0: + if stats["deleted"] > 0 or stats["compressed"] > 0: try: - print(f"[日志清理] 完成 - 删除:{stats['deleted']}, 压缩:{stats['compressed']}, " - f"释放:{stats['freed_space_mb']:.1f}MB") + print( + f"[日志清理] 完成 - 删除:{stats['deleted']}, 压缩:{stats['compressed']}, " + f"释放:{stats['freed_space_mb']:.1f}MB" + ) except Exception: pass @@ -483,6 +498,11 @@ def configure_logging( or keep_days is None or use_dated_logs is None ): + # 预初始化 rotation 相关变量,避免静态分析报未定义 + rotation_enabled = False + rotation_when = None + rotation_interval = 1 + try: import json @@ -494,7 +514,9 @@ def configure_logging( log_level = config.get("log_level", "INFO") if log_file is None: # 优先读取 log_unified_path,其次读取 logging.file_path - log_file = config.get("log_unified_path") or config.get("logging", {}).get("file_path", "logs/unified.log") + log_file = config.get("log_unified_path") or config.get( + "logging", {} + ).get("file_path", "logs/unified.log") log_config = config.get("logging", {}) if keep_days is None: keep_days = log_config.get("keep_days", 30) @@ -508,7 +530,11 @@ def configure_logging( compress_after_days = log_config.get("compress_after_days", 7) # 读取 rotation 配置(优先级高于函数默认参数) - rotation_cfg = log_config.get("rotation", {}) if isinstance(log_config, dict) else {} + rotation_cfg = ( + log_config.get("rotation", {}) + if isinstance(log_config, dict) + else {} + ) rotation_enabled = rotation_cfg.get("enabled", True) if rotation_cfg: # 支持按大小与按时间的配置 @@ -553,7 +579,9 @@ def configure_logging( "%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - " "[%(name)s:%(funcName)s:%(lineno)d] - [traceId:%(traceId)s] - %(message)s" ) - simple_format = "%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - %(message)s" + simple_format = ( + "%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - %(message)s" + ) # 控制台输出 if enable_console: @@ -591,7 +619,11 @@ def configure_logging( # 支持每次运行生成独立文件(per_run):在 base_filename 后追加运行时间戳,并在 handler 中关闭日期轮转 per_run = False try: - per_run = bool(log_config.get("per_run", True)) if isinstance(log_config, dict) else True + per_run = ( + bool(log_config.get("per_run", True)) + if isinstance(log_config, dict) + else True + ) except Exception: per_run = True @@ -679,6 +711,7 @@ def configure_logging( # 使用自定义Formatter以支持traceId try: from unified_logger import UnifiedFormatter + file_formatter = UnifiedFormatter( detailed_format, datefmt="%Y-%m-%d %H:%M:%S" ) @@ -687,13 +720,17 @@ def configure_logging( file_formatter = logging.Formatter( detailed_format, datefmt="%Y-%m-%d %H:%M:%S" ) + # 添加traceId占位符处理 class TraceIdFormatter(logging.Formatter): def format(self, record): - if not hasattr(record, 'traceId'): - record.traceId = 'N/A' + if not hasattr(record, "traceId"): + record.traceId = "N/A" return super().format(record) - file_formatter = TraceIdFormatter(detailed_format, datefmt="%Y-%m-%d %H:%M:%S") + + file_formatter = TraceIdFormatter( + detailed_format, datefmt="%Y-%m-%d %H:%M:%S" + ) file_formatter.default_msec_format = "%s.%03d" # 毫秒精度 file_handler.setFormatter(file_formatter) root_logger.addHandler(file_handler) @@ -989,7 +1026,9 @@ class LogRotationMonitor: print(f"[日志监控] CRITICAL: {message}") elif total_size_mb >= self.warning_size_mb: - message = f"日志总大小警告: {total_size_mb:.1f}MB >= {self.warning_size_mb}MB" + message = ( + f"日志总大小警告: {total_size_mb:.1f}MB >= {self.warning_size_mb}MB" + ) if self.alert_callback: self.alert_callback("WARNING", message) else: @@ -997,7 +1036,9 @@ class LogRotationMonitor: # 检查轮转频率 current_time = datetime.now() - if (current_time - self._last_check_time).total_seconds() >= 86400: # 24小时 + if ( + current_time - self._last_check_time + ).total_seconds() >= 86400: # 24小时 # 计算今天的文件数量 today_str = current_time.strftime("%Y-%m-%d") today_files = [f for f in log_files if today_str in f] @@ -1066,13 +1107,13 @@ def get_log_stats(logs_dir: str, base_name: str) -> Dict[str, Any]: 包含文件数量、总大小、压缩率等信息的字典 """ stats = { - 'total_files': 0, - 'total_size_mb': 0.0, - 'compressed_files': 0, - 'compressed_size_mb': 0.0, - 'compression_ratio': 0.0, - 'oldest_file': None, - 'newest_file': None, + "total_files": 0, + "total_size_mb": 0.0, + "compressed_files": 0, + "compressed_size_mb": 0.0, + "compression_ratio": 0.0, + "oldest_file": None, + "newest_file": None, } try: @@ -1082,7 +1123,7 @@ def get_log_stats(logs_dir: str, base_name: str) -> Dict[str, Any]: if not log_files: return stats - stats['total_files'] = len(log_files) + stats["total_files"] = len(log_files) # 计算大小统计 uncompressed_size = 0 @@ -1092,10 +1133,10 @@ def get_log_stats(logs_dir: str, base_name: str) -> Dict[str, Any]: for log_file in log_files: if os.path.exists(log_file): size = os.path.getsize(log_file) - stats['total_size_mb'] += size / 1024 / 1024 + stats["total_size_mb"] += size / 1024 / 1024 - if log_file.endswith('.gz'): - stats['compressed_files'] += 1 + if log_file.endswith(".gz"): + stats["compressed_files"] += 1 compressed_size += size else: uncompressed_size += size @@ -1110,13 +1151,15 @@ def get_log_stats(logs_dir: str, base_name: str) -> Dict[str, Any]: # 计算压缩率 if uncompressed_size > 0 and compressed_size > 0: # 压缩率 = 压缩后大小 / 原始大小 - stats['compression_ratio'] = compressed_size / (uncompressed_size + compressed_size) + stats["compression_ratio"] = compressed_size / ( + uncompressed_size + compressed_size + ) # 找出最老和最新的文件 if file_times: file_times.sort() - stats['oldest_file'] = os.path.basename(file_times[0][1]) - stats['newest_file'] = os.path.basename(file_times[-1][1]) + stats["oldest_file"] = os.path.basename(file_times[0][1]) + stats["newest_file"] = os.path.basename(file_times[-1][1]) except Exception: pass diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index 3fa05c7..24f0c01 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -123,6 +123,7 @@ class HelperFunctions: # OCR识别 from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore + name_res = preprocess_for_ocr(analyser, "开奖结果按钮") ocr_text = str(analyser.operation.analyse_pic_word(name_res, 0) or "") @@ -185,11 +186,14 @@ class HelperFunctions: """获取误识别记录文件路径""" try: import path_config + pic_dir = path_config.get_pic_dir() except (ImportError, ModuleNotFoundError, AttributeError): base_dir = os.path.dirname(__file__) pic_dir = os.path.join(base_dir, "pic") - false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") + false_positive_file = os.path.join( + pic_dir, "lottery_prize_captures", "false_positives.json" + ) return false_positive_file @staticmethod # type: ignore[misc] @@ -216,7 +220,12 @@ class HelperFunctions: try: with open(false_positive_file, "w", encoding="utf-8") as f: - json.dump({"false_positives": list(false_positives)}, f, ensure_ascii=False, indent=2) + json.dump( + {"false_positives": list(false_positives)}, + f, + ensure_ascii=False, + indent=2, + ) except OSError: # 写文件失败时忽略(非关键路径) pass @@ -261,12 +270,18 @@ class HelperFunctions: ) except Exception as e: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] - "开奖结果", "OCR点击执行失败,继续后续处理", x=btn_x, y=btn_y, error=str(e) + "开奖结果", + "OCR点击执行失败,继续后续处理", + x=btn_x, + y=btn_y, + error=str(e), ) # 等待点击生效,优先使用配置项 fudai_click_wait_seconds 回退到 0.8 秒 try: - delay_sec = float(getattr(analyser, "fudai_click_wait_seconds", 0.8) or 0.8) + delay_sec = float( + getattr(analyser, "fudai_click_wait_seconds", 0.8) or 0.8 + ) except Exception: delay_sec = 0.8 analyser.operation.delay(delay_sec) @@ -292,11 +307,14 @@ class HelperFunctions: # 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间 try: # 确保有最新截图 - analyser.operation.get_screenshot(analyser.device_id, use_service=False) + analyser.operation.get_screenshot( + analyser.device_id, use_service=False + ) # 使用统一的截图路径配置 try: import path_config + src = path_config.get_screenshot_path() pic_dir = path_config.get_pic_dir() except Exception: diff --git a/tools/tmp_check_logging.py b/tools/tmp_check_logging.py index 65a5fbb..7d16190 100644 --- a/tools/tmp_check_logging.py +++ b/tools/tmp_check_logging.py @@ -5,16 +5,33 @@ import logging.handlers as lh # Configure logging using current config douyin_logging.configure_logging() root = logging.getLogger() -print('handlers:', [type(h).__name__ for h in root.handlers]) +print("handlers:", [type(h).__name__ for h in root.handlers]) for h in root.handlers: - fname = getattr(h, 'baseFilename', getattr(h, 'filename', None)) + fname = getattr(h, "baseFilename", getattr(h, "filename", None)) print(type(h).__name__, fname) # RotatingDatedFileHandler specific - if hasattr(h, 'max_bytes'): - print(' max_bytes =', getattr(h, 'max_bytes', None), 'backup_count =', getattr(h, 'backup_count', None)) + if hasattr(h, "max_bytes"): + print( + " max_bytes =", + getattr(h, "max_bytes", None), + "backup_count =", + getattr(h, "backup_count", None), + ) # RotatingFileHandler if isinstance(h, lh.RotatingFileHandler): - print(' RotatingFileHandler maxBytes =', getattr(h, 'maxBytes', None), 'backupCount =', getattr(h, 'backupCount', None)) + print( + " RotatingFileHandler maxBytes =", + getattr(h, "maxBytes", None), + "backupCount =", + getattr(h, "backupCount", None), + ) if isinstance(h, lh.TimedRotatingFileHandler): - print(' TimedRotating when =', getattr(h, 'when', None), 'interval =', getattr(h, 'interval', None), 'backupCount =', getattr(h, 'backupCount', None)) + print( + " TimedRotating when =", + getattr(h, "when", None), + "interval =", + getattr(h, "interval", None), + "backupCount =", + getattr(h, "backupCount", None), + )