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