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