-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlog_helper.py
More file actions
64 lines (50 loc) · 1.58 KB
/
log_helper.py
File metadata and controls
64 lines (50 loc) · 1.58 KB
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
import structlog
import logging
import os
import sys
levels = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
# Configure structlog to be machine-readable first and foremost
# while still making it easy for humans to parse
# End result (without additional bindings) is JSON like this:
#
# { "logger": "module param"
# "message": "this is a test log event",
# "level": "info",
# "timestamp": "2023-11-01 18:50:47"}
#
def get_structlog(module):
structlog.configure(
processors=[
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.EventRenamer("message"),
structlog.processors.JSONRenderer(),
],
context_class=dict,
logger_factory=structlog.PrintLoggerFactory(),
)
return structlog.get_logger(module)
def standard_logger(module):
logger = logging.getLogger(module)
if logger.hasHandlers():
logger.handlers = []
console_log = logging.StreamHandler(stream=sys.stdout)
log_level = os.environ.get('LOG_LEVEL', 'info').lower()
logger.setLevel(levels[log_level])
console_log.setLevel(levels[log_level])
formatter = logging.Formatter(
'%(asctime)s | %(name)s | %(levelname)s: %(message)s')
console_log.setFormatter(formatter)
logger.addHandler(console_log)
return logger
def create_log(module, json=False):
if (json):
return get_structlog(module)
else:
return standard_logger(module)