-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlog_helper.py
More file actions
72 lines (58 loc) · 2.02 KB
/
log_helper.py
File metadata and controls
72 lines (58 loc) · 2.02 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
65
66
67
68
69
70
71
72
import logging
import os
import structlog
import sys
levels = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
def get_structlog(module):
"""
Standard logging without additional bindings looks as follows:
{
"level": "info",
"timestamp": "2026-01-01T12:00:00.613719Z",
"logger": "module param",
"message": "this is a test log event"
}
Note that: 1) you should *NOT* use the same module name for a structlog
and for a standard logger, and 2) using bind_contextvars will bind
variables to *all* loggers. To bind a context variable on one logger
without binding it to others, use `logger = logger.bind(contextvar=0)`.
"""
logger = logging.getLogger(module)
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(os.environ.get('LOG_LEVEL', 'INFO').upper())
logger.propagate = False # Prevents double logging
return structlog.wrap_logger(
logger,
processors=[
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt='iso'),
structlog.stdlib.add_logger_name,
structlog.processors.EventRenamer('message'),
structlog.processors.JSONRenderer(),
]
)
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)