-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice_logger.py
75 lines (59 loc) · 1.9 KB
/
service_logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import sys
import io
CRITICAL = const(50)
ERROR = const(40)
WARNING = const(30)
INFO = const(20)
DEBUG = const(10)
NOTSET = const(0)
_level_dict = {
"CRITICAL": CRITICAL,
"ERROR": ERROR,
"WARNING": WARNING,
"INFO": INFO,
"DEBUG": DEBUG,
}
class ServiceLogger:
def __init__(self, logger, name, level=INFO):
self.name = name
self.level = _level_dict.get(level, INFO)
self.logger = logger
def setLevel(self, level):
self.level = _level_dict.get(level, INFO)
def isEnabledFor(self, level):
return level >= self.getEffectiveLevel()
def getEffectiveLevel(self):
return self.level
def getLoggerName(self, cname=None):
if not cname:
return f"{self.name}.service"
else:
return f"{self.name}.service.{cname}"
def log(self, level, msg, *args, **kwargs):
if self.isEnabledFor(level):
self.logger.log(
level,
f"[{self.getLoggerName(kwargs.get('cname'))}] {msg}",
*args,
)
def debug(self, msg, *args, **kwargs):
self.log(DEBUG, msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
self.log(INFO, msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
self.log(WARNING, msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
self.log(ERROR, msg, *args, **kwargs)
def critical(self, msg, *args, **kwargs):
self.log(CRITICAL, msg, *args, **kwargs)
def exception(self, msg, *args, exc_info=True, **kwargs):
self.log(ERROR, msg, *args, **kwargs)
tb = None
if isinstance(exc_info, BaseException):
tb = exc_info
elif hasattr(sys, "exc_info"):
tb = sys.exc_info()[1]
if tb:
buf = io.StringIO()
sys.print_exception(tb, buf)
self.log(ERROR, buf.getvalue())