|
4 | 4 | import json
|
5 | 5 | import logging
|
6 | 6 | import os
|
7 |
| -import time |
8 | 7 | from abc import ABCMeta, abstractmethod
|
9 | 8 | from datetime import datetime, timezone
|
10 | 9 | from functools import partial
|
|
42 | 41 | )
|
43 | 42 |
|
44 | 43 |
|
| 44 | +def local_tz_converter(secs: float, utc: bool) -> datetime: |
| 45 | + if utc: |
| 46 | + return datetime.fromtimestamp(secs, tz=timezone.utc) |
| 47 | + return datetime.fromtimestamp(secs).astimezone() |
| 48 | + |
| 49 | + |
45 | 50 | class BasePowertoolsFormatter(logging.Formatter, metaclass=ABCMeta):
|
46 | 51 | @abstractmethod
|
47 | 52 | def append_keys(self, **additional_keys) -> None:
|
@@ -142,9 +147,6 @@ def __init__(
|
142 | 147 | self.update_formatter = self.append_keys # alias to old method
|
143 | 148 | self.use_rfc3339_iso8601 = use_rfc3339
|
144 | 149 |
|
145 |
| - if self.utc: |
146 |
| - self.converter = time.gmtime |
147 |
| - |
148 | 150 | self.keys_combined = {**self._build_default_keys(), **kwargs}
|
149 | 151 | self.log_format.update(**self.keys_combined)
|
150 | 152 |
|
@@ -178,11 +180,10 @@ def formatTime(self, record: logging.LogRecord, datefmt: Optional[str] = None) -
|
178 | 180 | ts_as_datetime = datetime.fromtimestamp(record.created, tz=timezone.utc)
|
179 | 181 | else:
|
180 | 182 | ts_as_datetime = datetime.fromtimestamp(record.created).astimezone()
|
181 |
| - |
182 | 183 | return ts_as_datetime.isoformat(timespec="milliseconds") # 2022-10-27T17:42:26.841+0200
|
183 | 184 |
|
184 | 185 | # converts to local/UTC TZ as struct time
|
185 |
| - record_ts = self.converter(record.created) |
| 186 | + record_ts = local_tz_converter(record.created, self.utc) |
186 | 187 |
|
187 | 188 | if datefmt is None: # pragma: no cover, it'll always be None in std logging, but mypy
|
188 | 189 | datefmt = self.datefmt
|
@@ -211,11 +212,11 @@ def formatTime(self, record: logging.LogRecord, datefmt: Optional[str] = None) -
|
211 | 212 | # Only time format codes being used
|
212 | 213 | elif datefmt:
|
213 | 214 | custom_fmt = datefmt.replace(self.custom_ms_time_directive, msecs)
|
214 |
| - return time.strftime(custom_fmt, record_ts) |
| 215 | + return record_ts.strftime(custom_fmt) |
215 | 216 |
|
216 | 217 | # Use default fmt: 2021-05-03 10:20:19,650+0200
|
217 | 218 | custom_fmt = self.default_time_format.replace(self.custom_ms_time_directive, msecs)
|
218 |
| - return time.strftime(custom_fmt, record_ts) |
| 219 | + return record_ts.strftime(custom_fmt) |
219 | 220 |
|
220 | 221 | def append_keys(self, **additional_keys) -> None:
|
221 | 222 | self.log_format.update(additional_keys)
|
|
0 commit comments