添加日志过滤器, 降低相同日志输出频率
This commit is contained in:
parent
cfc8f80954
commit
e6a8571626
@ -12,6 +12,10 @@ from dataclasses import dataclass
|
|||||||
from collections import deque
|
from collections import deque
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
|
|
||||||
|
from util.log_util import TimeBasedDuplicateFilter
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from ultralytics import YOLO
|
from ultralytics import YOLO
|
||||||
except ImportError:
|
except ImportError:
|
||||||
@ -28,6 +32,9 @@ logging.basicConfig(
|
|||||||
)
|
)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 5为时间间隔,单位s. 5s内不会输出相同日志
|
||||||
|
logger.addFilter(TimeBasedDuplicateFilter(5))
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class DetectionResult:
|
class DetectionResult:
|
||||||
"""检测结果数据类"""
|
"""检测结果数据类"""
|
||||||
|
|||||||
29
util/log_util.py
Normal file
29
util/log_util.py
Normal file
@ -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 # 记录这条日志
|
||||||
Loading…
Reference in New Issue
Block a user