diff --git a/rtsp_processor_1.py b/rtsp_processor_1.py index 98ea2cf..a26c3a9 100644 --- a/rtsp_processor_1.py +++ b/rtsp_processor_1.py @@ -12,6 +12,10 @@ from dataclasses import dataclass from collections import deque import yaml + +from util.log_util import TimeBasedDuplicateFilter + + try: from ultralytics import YOLO except ImportError: @@ -28,6 +32,9 @@ logging.basicConfig( ) logger = logging.getLogger(__name__) +# 5为时间间隔,单位s. 5s内不会输出相同日志 +logger.addFilter(TimeBasedDuplicateFilter(5)) + @dataclass class DetectionResult: """检测结果数据类""" diff --git a/util/log_util.py b/util/log_util.py new file mode 100644 index 0000000..d84e3d6 --- /dev/null +++ b/util/log_util.py @@ -0,0 +1,29 @@ +import logging +import time +from collections import defaultdict + +class TimeBasedDuplicateFilter(logging.Filter): + """ + 过滤 5 秒内的重复日志 + """ + def __init__(self, interval=5): + super().__init__() + self.interval = interval # 时间间隔(秒) + self.last_log = defaultdict(dict) # 记录最近日志的时间 {logger_name: {msg: last_time}} + + def filter(self, record): + current_time = time.time() + msg = record.getMessage() + logger_name = record.name + + # 如果这条日志在 5 秒内已经记录过,则过滤掉 + if ( + logger_name in self.last_log + and msg in self.last_log[logger_name] + and (current_time - self.last_log[logger_name][msg]) < self.interval + ): + return False # 不记录这条日志 + + # 更新最近日志时间 + self.last_log[logger_name][msg] = current_time + return True # 记录这条日志 \ No newline at end of file