Skip to content

Commit 7c71d69

Browse files
authored
fix(logger): stop adding milliseconds twice when use_datetime_directive is set (#8632)
Signed-off-by: Sebastian Turner <sebastiant3484@gmail.com>
1 parent c14bb80 commit 7c71d69

2 files changed

Lines changed: 21 additions & 5 deletions

File tree

‎aws_lambda_powertools/logging/formatter.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -237,13 +237,11 @@ def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -> s
237237
# by default, those migrating from std logging will use time format codes
238238
# https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
239239
if self.use_datetime_directive and datefmt:
240-
# record.msecs are microseconds, divide by 1000 to get milliseconds
241-
timestamp = record.created + record.msecs / 1000
242-
240+
# record.created already carries the sub-second part, so it is used as is
243241
if self.utc:
244-
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
242+
dt = datetime.fromtimestamp(record.created, tz=timezone.utc)
245243
else:
246-
dt = datetime.fromtimestamp(timestamp).astimezone()
244+
dt = datetime.fromtimestamp(record.created).astimezone()
247245

248246
custom_fmt = datefmt.replace(self.custom_ms_time_directive, msecs)
249247
return dt.strftime(custom_fmt)

‎tests/functional/logger/required_dependencies/test_logger.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,6 +1084,24 @@ def test_use_datetime(stdout, service_name, utc):
10841084
)
10851085

10861086

1087+
@pytest.mark.parametrize("utc", [False, True])
1088+
def test_use_datetime_does_not_shift_timestamp(utc):
1089+
# GIVEN a formatter using datetime directives
1090+
formatter = LambdaPowertoolsFormatter(datefmt="%Y-%m-%d %H:%M:%S.%F|%f", use_datetime_directive=True, utc=utc)
1091+
1092+
# AND a log record created 750 milliseconds after a full second
1093+
record = logging.LogRecord("test", logging.INFO, __file__, 1, "message", None, None)
1094+
record.created = 1700000000.75
1095+
record.msecs = 750.0
1096+
1097+
# WHEN the timestamp is formatted
1098+
timestamp = formatter.formatTime(record, formatter.datefmt)
1099+
1100+
# THEN it matches the time the record was created
1101+
expected = datetime.fromtimestamp(record.created, tz=timezone.utc if utc else None)
1102+
assert timestamp == expected.strftime("%Y-%m-%d %H:%M:%S.750|%f")
1103+
1104+
10871105
@pytest.mark.parametrize("utc", [False, True])
10881106
def test_use_rfc3339_iso8601(stdout, service_name, utc):
10891107
# GIVEN

0 commit comments

Comments
 (0)