isotopic_logging.LoggerProxy.__getattr__()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3
Metric Value
cc 3
dl 0
loc 22
ccs 8
cts 8
cp 1
crap 3
rs 9.2

1 Method

Rating   Name   Duplication   Size   Complexity  
A isotopic_logging.LoggerProxy.wrapper() 0 3 1
1
# -*- coding: utf-8 -*-
2
3 1
from functools import wraps
4
5
6 1
_wrapped_method_names = {
7
    'debug', 'info', 'warn', 'warning', 'error', 'fatal', 'critical',
8
    'exception',
9
}
10
11
12 1
class LoggerProxy(object):
13
    """
14
    Proxy for `logging.Logger` and classes inherited from it.
15
16
    Automatically injects prefixes to messages which are send to log.
17
    This reduces overhead of
18
19
        >>> logger.log_level(injector.mark("mesage"))
20
21
    just to
22
23
        >>> logger.log_level("message")
24
    """
25
26 1
    def __init__(self, logger, injector):
27 1
        self._original = logger
28 1
        self.injector = injector
29
30 1
    @property
31
    def elapsed_time(self):
32 1
        return self.injector.elapsed_time
33
34 1
    def format_elapsed_time(self, fmt=None):
35 1
        return self.injector.format_elapsed_time(fmt)
36
37 1
    def __getattr__(self, name):
38
        """
39
        Get attribute of original logger or wrapped version of methods used
40
        for logging.
41
42
        We do not wrap calls to `debug`, `info`, etc. directly. This is because
43
        those levels are default, but their list may be extended, for example,
44
        like in case of `python-verboselogs` library.
45
        """
46 1
        result = getattr(self._original, name)
47
48 1
        if name in _wrapped_method_names:
49
50 1
            @wraps(result)
51
            def wrapper(message, *args, **kwargs):
52 1
                return result(self.injector.mark(message), *args, **kwargs)
53
54
            # Cache wrapper, so it won't be constructed again for future calls.
55 1
            setattr(self, name, wrapper)
56 1
            return wrapper
57
58
        return result
59