| Total Complexity | 8 |
| Total Lines | 45 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | |||
| 2 | from collections import OrderedDict |
||
| 3 | from logging import LogRecord |
||
| 4 | from threading import Lock |
||
| 5 | |||
| 6 | |||
| 7 | class RepeateMessageFilter: |
||
| 8 | lockout_time: float |
||
| 9 | cache_size: int |
||
| 10 | _cache: OrderedDict[tuple, float] |
||
| 11 | _lock: Lock |
||
| 12 | |||
| 13 | def __init__(self, lockout_time: float, cache_size: int = 512): |
||
| 14 | self.lockout_time = lockout_time |
||
| 15 | self.cache_size = cache_size |
||
| 16 | self._cache = OrderedDict() |
||
| 17 | self._lock = Lock() |
||
| 18 | |||
| 19 | def filter(self, record: LogRecord) -> bool: |
||
| 20 | key = self._record_key(record) |
||
| 21 | current_time = record.created |
||
| 22 | with self._lock: |
||
| 23 | if key not in self._cache: |
||
| 24 | self._cache[key] = current_time |
||
| 25 | if len(self._cache) > self.cache_size: |
||
| 26 | self._cache.popitem(last=False) |
||
| 27 | return True |
||
| 28 | elif current_time - self._cache[key] > self.lockout_time: |
||
| 29 | self._cache[key] = current_time |
||
| 30 | self._cache.move_to_end(key) |
||
| 31 | if len(self._cache) > self.cache_size: |
||
| 32 | self._cache.popitem(last=False) |
||
| 33 | return True |
||
| 34 | return False |
||
| 35 | |||
| 36 | @staticmethod |
||
| 37 | def _record_key(record: LogRecord): |
||
| 38 | return ( |
||
| 39 | record.pathname, |
||
| 40 | record.module, |
||
| 41 | record.lineno, |
||
| 42 | record.levelno, |
||
| 43 | record.msg, |
||
| 44 | record.args |
||
| 45 | ) |
||
| 46 |