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