Belle II Software  release-08-01-10
logfilter.py
1 
8 """
9 Log Filter class to replace string occurences in log messages to simplify testing
10 """
11 import 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 = out
29 
30  self._replacements_replacements = replacements
31 
32  self._regex_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_regex.sub(lambda m: self._replacements_replacements[m[0]], data)
37  self._out_out.write(replaced)
38 
39  def __getattr__(self, name):
40  """Forward all other methods from the out stream"""
41  return getattr(self._out_out, name)
def __init__(self, out, replacements)
Definition: logfilter.py:20
_regex
build a regular expression from dictionary keys
Definition: logfilter.py:32