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 # 记录这条日志