-
Notifications
You must be signed in to change notification settings - Fork 2
/
filter.py
89 lines (71 loc) · 2.12 KB
/
filter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from typing import Callable
import structlog
__all__ = [
"FilterKeys",
"FilterMethods",
"exclude_keys",
"exclude_methods",
"only_keys",
"only_methods",
]
class FilterMethods:
"""
A processor that filters log events based on the name of the method that
was called on the BoundLogger.
"""
def __init__(
self,
predicate: Callable[[str], bool],
):
self.predicate = predicate
def __call__(
self,
logger: structlog.types.WrappedLogger,
method_name: str,
event_dict: structlog.types.EventDict,
) -> structlog.types.EventDict:
if self.predicate(method_name):
return event_dict
else:
raise structlog.DropEvent
def only_methods(*names: str) -> FilterMethods:
"""
A specialisation of FilterMethods that only passes log events through if
the method name is contained in 'names'.
"""
return FilterMethods(lambda name: name in names)
def exclude_methods(*names: str) -> FilterMethods:
"""
A specialisation of FilterMethods that drops log events if the method name
is contained in 'names'.
"""
return FilterMethods(lambda name: name not in names)
class FilterKeys:
"""
A processor that filters the keys included in the event dictionary.
"""
def __init__(
self,
predicate: Callable[[str], bool],
):
self.predicate = predicate
def __call__(
self,
logger: structlog.types.WrappedLogger,
method_name: str,
event_dict: structlog.types.EventDict,
) -> structlog.types.EventDict:
for key in set(event_dict.keys()):
if not self.predicate(key):
del event_dict[key]
return event_dict
def only_keys(*keys: str) -> FilterKeys:
"""
A specialisation of FilterKeys that only keeps the keys contained in 'keys'.
"""
return FilterKeys(lambda key: key in keys)
def exclude_keys(*keys: str) -> FilterKeys:
"""
A specialisation of FilterKeys that removes the keys contained in 'keys'.
"""
return FilterKeys(lambda key: key not in keys)