SND@LHC Software
Loading...
Searching...
No Matches
method_logger.py
Go to the documentation of this file.
1# -*- coding: utf-8 -*-
2
3from __future__ import print_function
4from functools import wraps
5import sys
6import six # For compatibility with both Python 2 and 3
7
8class MethodLogger(object):
9 """
10 This class wraps a instance of an arbitrary class, intercepts all its
11 method calls and logs them to a file (default: `sys.stdout`).
12
13 >>> import method_logger as ml
14 >>> from StringIO import StringIO
15 >>> class TestClass(object):
16 ... def __init__(self):
17 ... pass
18 ... def func(*args, **kwargs):
19 ... pass
20 ...
21 >>> cl = TestClass()
22 >>> sink = StringIO()
23 >>> lg = ml.MethodLogger(cl, sink=sink)
24 >>> lg.func(3, y=8, foo='bar')
25 >>> sink.getvalue()
26 "TestClass.func(3, y=8, foo='bar')\\n"
27 >>> sink.close()
28 """
29 def __init__(self, wrapped_instance, sink=sys.stdout):
30 self._class = wrapped_instance
31 self._sink = sink
32 self._prefix = type(wrapped_instance).__name__ + '.'
33
34 def method_logger(self, met):
35 qualified_name = self._prefix + str(met.__name__)
36 @wraps(met)
37 def _logger(*args, **kwargs):
38 args_str = ', '.join(repr(arg) for arg in args)
39 kwargs_str = ', '.join(str(k) + '=' + repr(v) for (k,v) in six.iteritems(kwargs))
40 all_args_str = args_str + (', ' if len(kwargs_str) > 0 else '') + kwargs_str
41 print('{0}({1})'.format(qualified_name, all_args_str), file=self._sink)
42 return met.__call__(*args, **kwargs)
43 return _logger
44
45 def __getattr__(self, attr):
46 return self.method_logger(getattr(self._class, attr))
__init__(self, wrapped_instance, sink=sys.stdout)