Belle II Software development
logfilter.py
1
8"""
9Log Filter class to replace string occurences in log messages to simplify testing
10"""
11import re
12
13
15 """
16 Simple class to intercept anything written to python stdout and replace
17 a given set of strings with placehholders to improve reproducibility.
18 """
19
20 def __init__(self, out, replacements):
21 """Setup the forwarding and replacements
22
23 Parameters:
24 out (file object): Where to forward the output too
25 replacements (dict(str, str)): Dictionary of strings and their replacements
26 """
27
28 self._out = out
29
30 self._replacements = replacements
31
32 self._regex = re.compile("|".join(re.escape(e) for e in replacements))
33
34 def write(self, data):
35 """Check all messages for strings to replace"""
36 replaced = self._regex.sub(lambda m: self._replacements[m[0]], data)
37 self._out.write(replaced)
38
39 def __getattr__(self, name):
40 """Forward all other methods from the out stream"""
41 return getattr(self._out, name)
def __init__(self, out, replacements)
Definition: logfilter.py:20
_regex
build a regular expression from dictionary keys
Definition: logfilter.py:32
Definition: python.py:1