-
Notifications
You must be signed in to change notification settings - Fork 2
/
timestamper.py
39 lines (31 loc) · 1.04 KB
/
timestamper.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
import datetime
from typing import Callable
import structlog
__all__ = ["TimezoneAwareTimeStamper"]
def _default_now() -> datetime.datetime:
return datetime.datetime.now().astimezone() # pragma: no cover
class TimezoneAwareTimeStamper:
"""
A workaround for the fact that structlog.processors.TimeStamper only
supports UTC or naive (timezone-less) timestamps. Use this if you
want to make the timezone explicit in the formatted log message.
Full datetime.strftime syntax is supported.
"""
def __init__(
self,
*,
format: str = "%Y-%m-%dT%H:%M:%S%z",
key: str = "timestamp",
now: Callable[[], datetime.datetime] = _default_now,
):
self.format = format
self.key = key
self.now = now
def __call__(
self,
logger: structlog.types.WrappedLogger,
method_name: str,
event_dict: structlog.types.EventDict,
) -> structlog.types.EventDict:
event_dict[self.key] = self.now().strftime(self.format)
return event_dict