Skip to content

Timestamp timezone stamper

Add a timestamp to event_dict.

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.

Parameters:

Name Type Description Default
fmt str | Literal['iso']

strftime format string, or "iso" for ISO 8601 <https://en.wikipedia.org/wiki/ISO_8601>_

'%Y-%m-%dT%H:%M:%S%z'
key str

Target key in event_dict for added timestamps.

'timestamp'
now Callable[[], datetime]

Function that returns the current time when called

_default_now
Source code in nava/platform/cli/logging/timestamp_timezone_stamper.py
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
class TimezoneAwareTimeStamper:
    """Add a timestamp to ``event_dict``.

    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.

    Args:
        fmt:
            strftime format string, or ``"iso"`` for `ISO 8601
            <https://en.wikipedia.org/wiki/ISO_8601>`_

        key: Target key in *event_dict* for added timestamps.

        now: Function that returns the current time when called


    """

    __slots__ = ("fmt", "key", "now")

    def __init__(
        self,
        *,
        fmt: str | Literal["iso"] = "%Y-%m-%dT%H:%M:%S%z",
        key: str = "timestamp",
        now: Callable[[], datetime.datetime] = _default_now,
    ):
        self.fmt = fmt
        self.key = key
        self.now = now

    def __call__(
        self,
        logger: structlog.types.WrappedLogger,
        method_name: str,
        event_dict: structlog.types.EventDict,
    ) -> structlog.types.EventDict:
        time = self.now().isoformat() if self.fmt == "iso" else self.now().strftime(self.fmt)
        event_dict[self.key] = time
        return event_dict