Belle II Software  release-06-02-00
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  def __init__(self, out, replacements):
20  """Setup the forwarding and replacements
21 
22  Parameters:
23  out (file object): Where to forward the output too
24  replacements (dict(str, str)): Dictionary of strings and their replacements
25  """
26 
27  self._out_out = out
28 
29  self._replacements_replacements = replacements
30 
31  self._regex_regex = re.compile("|".join(re.escape(e) for e in replacements))
32 
33  def write(self, data):
34  """Check all messages for strings to replace"""
35  replaced = self._regex_regex.sub(lambda m: self._replacements_replacements[m[0]], data)
36  self._out_out.write(replaced)
37 
38  def __getattr__(self, name):
39  """Forward all other methods from the out stream"""
40  return getattr(self._out_out, name)
def __init__(self, out, replacements)
Definition: logfilter.py:19
_regex
build a regular expression from dictionary keys
Definition: logfilter.py:31