-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.py
More file actions
71 lines (57 loc) · 2.14 KB
/
logger.py
File metadata and controls
71 lines (57 loc) · 2.14 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
import logging
from datetime import datetime
from typing import TYPE_CHECKING, Any, MutableMapping
from pythonjsonlogger import jsonlogger
class CustomJsonFormatter(jsonlogger.JsonFormatter):
def add_fields(
self,
log_record: dict[str, Any],
record: logging.LogRecord,
message_dict: dict[str, Any],
) -> None:
super(CustomJsonFormatter, self).add_fields(
log_record, record, message_dict
)
if not log_record.get("timestamp"):
# this doesn't use record.created, so it is slightly off
now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
log_record["timestamp"] = now
if log_record.get("level"):
log_record["level"] = log_record["level"].upper()
else:
log_record["level"] = record.levelname
formatter = CustomJsonFormatter()
# Create a custom logger
logger = logging.getLogger(name="tuhag")
# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler("file.log")
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.DEBUG)
# Create formatters and add it to handlers
c_handler.setFormatter(formatter)
f_handler.setFormatter(formatter)
# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)
if TYPE_CHECKING:
LoggerAdapterBase = logging.LoggerAdapter[logging.Logger]
else:
LoggerAdapterBase = logging.LoggerAdapter
class CustomLoggerAdapter(LoggerAdapterBase):
def process(
self, msg: str, kwargs: MutableMapping[str, Any]
) -> tuple[str, MutableMapping[str, Any]]:
"""
The `extra` in `LoggerAdapter` takes precedence over the `extra` argument in the logging call's argument.
This CustomLoggerAdapter merges the 2 dicts together
"""
if "extra" in kwargs:
# this merges the two extras together
# self.extra can be None
merged = {**(self.extra or {}), **kwargs["extra"]}
kwargs["extra"] = merged
else:
# when the logging call does not have the `extra` argument
kwargs["extra"] = self.extra
return msg, kwargs