Skip to content

Commit 88fe303

Browse files
committed
Switch to use_datetime
1 parent 38e5f59 commit 88fe303

File tree

3 files changed

+25
-21
lines changed

3 files changed

+25
-21
lines changed

aws_lambda_powertools/logging/formatter.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def __init__(
6262
json_deserializer: Optional[Callable[[Union[Dict, str, bool, int, float]], str]] = None,
6363
json_default: Optional[Callable[[Any], Any]] = None,
6464
datefmt: Optional[str] = None,
65-
datetime_fmt: Optional[str] = None,
65+
use_datetime: bool = False,
6666
log_record_order: Optional[List[str]] = None,
6767
utc: bool = False,
6868
**kwargs,
@@ -88,13 +88,12 @@ def __init__(
8888
Only used when no custom JSON encoder is set
8989
9090
datefmt : str, optional
91-
String directives (strftime) to format log timestamp using `time`. Only one of `datefmt`
92-
and `datetime_fmt` should be specified.
91+
String directives (strftime) to format log timestamp.
9392
94-
See https://docs.python.org/3/library/time.html#time.strftime
95-
datetime_fmt : str, optional
96-
String directives (strftime) to format log timestamp using `datetime`. Only one of
97-
`datefmt` and `datetime_fmt` should be specified.
93+
See https://docs.python.org/3/library/time.html#time.strftime or
94+
use_datetime: str, optional
95+
Interpret `datefmt` as a format string for `datetime.datetime.strftime`, rather than
96+
`time.strftime`.
9897
9998
See https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior . This
10099
also supports a custom %F directive for milliseconds.
@@ -110,10 +109,8 @@ def __init__(
110109
self.json_default = json_default or str
111110
self.json_serializer = json_serializer or partial(json.dumps, default=self.json_default, separators=(",", ":"))
112111

113-
if datefmt and datetime_fmt:
114-
raise ValueError(f"at most one of datefmt {datefmt!r} and datetime_fmt {datetime_fmt!r} can be specified")
115112
self.datefmt = datefmt
116-
self.datetime_fmt = datetime_fmt
113+
self.use_datetime = use_datetime
117114

118115
self.utc = utc
119116
self.log_record_order = log_record_order or ["level", "location", "message", "timestamp"]
@@ -145,25 +142,28 @@ def format(self, record: logging.LogRecord) -> str: # noqa: A003
145142
def formatTime(self, record: logging.LogRecord, datefmt: Optional[str] = None) -> str:
146143
record_ts = self.converter(record.created) # type: ignore
147144

145+
if datefmt is None:
146+
datefmt = self.datefmt
147+
148148
# NOTE: Python `time.strftime` doesn't provide msec directives
149149
# so we create a custom one (%F) and replace logging record ts
150150
# Reason 2 is that std logging doesn't support msec after TZ
151151
msecs = "%03d" % record.msecs
152152

153-
if datefmt or self.datefmt:
154-
return time.strftime(datefmt or self.datefmt, record_ts)
155-
156-
elif self.datetime_fmt:
153+
if self.use_datetime:
157154
timestamp = record.created + record.msecs / 1000
158155

159156
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
160157
if not self.utc:
161158
# convert back to local time
162159
dt = dt.astimezone()
163160

164-
custom_fmt = self.datetime_fmt.replace(self.custom_ms_time_directive, msecs)
161+
custom_fmt = (datefmt or self.default_time_format).replace(self.custom_ms_time_directive, msecs)
165162
return dt.strftime(custom_fmt)
166163

164+
elif datefmt:
165+
return time.strftime(datefmt, record_ts)
166+
167167
custom_fmt = self.default_time_format.replace(self.custom_ms_time_directive, msecs)
168168
return time.strftime(custom_fmt, record_ts)
169169

aws_lambda_powertools/logging/logger.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,13 @@ class Logger(logging.Logger): # lgtm [py/missing-call-to-init]
8181
---------------------------------------------
8282
datefmt: str, optional
8383
String directives (strftime) to format log timestamp using `time`, by default it uses RFC
84-
3339. Only one of `datefmt` and `datetime_fmt` should be specified.
85-
datetime_fmt : str, optional
86-
String directives (strftime) to format log timestamp using `datetime`. Only one of `datefmt`
87-
and `datetime_fmt` should be specified.
84+
3339.
85+
use_datetime: str, optional
86+
Interpret `datefmt` as a format string for `datetime.datetime.strftime`, rather than
87+
`time.strftime`.
88+
89+
See https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior . This
90+
also supports a custom %F directive for milliseconds.
8891
json_serializer : Callable, optional
8992
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
9093
json_deserializer : Callable, optional

tests/functional/test_logger.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -615,12 +615,13 @@ def handler(event, context, my_custom_option=None):
615615

616616

617617
@pytest.mark.parametrize("utc", [False, True])
618-
def test_datetime_fmt(stdout, service_name, utc):
618+
def test_use_datetime(stdout, service_name, utc):
619619
# GIVEN
620620
logger = Logger(
621621
service=service_name,
622622
stream=stdout,
623-
datetime_fmt="custom timestamp: milliseconds=%F microseconds=%f timezone=%z",
623+
datefmt="custom timestamp: milliseconds=%F microseconds=%f timezone=%z",
624+
use_datetime=True,
624625
utc=utc,
625626
)
626627

0 commit comments

Comments
 (0)