From e6a857162642c24b4c2cd1cc10f67233e8e32737 Mon Sep 17 00:00:00 2001 From: haotian <2421912570@qq.com> Date: Wed, 17 Sep 2025 11:36:48 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=97=A5=E5=BF=97=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=E5=99=A8,=20=E9=99=8D=E4=BD=8E=E7=9B=B8=E5=90=8C?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=BE=93=E5=87=BA=E9=A2=91=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rtsp_processor_1.py | 7 +++++++ util/log_util.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 util/log_util.py 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