Skip to content
This repository was archived by the owner on Dec 21, 2024. It is now read-only.

Commit b214640

Browse files
committed
Add timezone to timestamp
Before this commit, when a JsonFormatter is created with the timestamp= True parameter, it used utcnow(). Which is not time when the log record was created, but when the field was added. Also, utcnow is not timezone aware, so the serialized datetime is missing the timezone designator at the end. This commit uses the time at which the log record was created and sets the timezone to UTC, which results in an additional "+000" end
1 parent 6d43bde commit b214640

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/pythonjsonlogger/jsonlogger.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import logging
66
import json
77
import re
8-
from datetime import date, datetime, time
8+
from datetime import date, datetime, time, timezone
99
import traceback
1010
import importlib
1111

@@ -154,7 +154,7 @@ def add_fields(self, log_record, record, message_dict):
154154

155155
if self.timestamp:
156156
key = self.timestamp if type(self.timestamp) == str else 'timestamp'
157-
log_record[key] = datetime.utcnow()
157+
log_record[key] = datetime.fromtimestamp(record.created, tz=timezone.utc)
158158

159159
def process_log_record(self, log_record):
160160
"""

tests/tests.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
# -*- coding: utf-8 -*-
22
import unittest
3+
import unittest.mock
34
import logging
45
import json
56
import sys
67
import traceback
78
import random
89

910
try:
10-
import xmlrunner
11+
import xmlrunner # noqa
1112
except ImportError:
1213
pass
1314

1415
try:
15-
from StringIO import StringIO
16+
from StringIO import StringIO # noqa
1617
except ImportError:
1718
# Python 3 Support
1819
from io import StringIO
@@ -131,6 +132,17 @@ def testJsonDefaultEncoder(self):
131132
self.assertEqual(logJson.get("otherdatetimeagain"),
132133
"1900-01-01T00:00:00")
133134

135+
@unittest.mock.patch('time.time', return_value=1500000000.0)
136+
def testJsonDefaultEncoderWithTimestamp(self, time_mock):
137+
fr = jsonlogger.JsonFormatter(timestamp=True)
138+
self.logHandler.setFormatter(fr)
139+
140+
self.logger.info("Hello")
141+
142+
self.assertTrue(time_mock.called)
143+
logJson = json.loads(self.buffer.getvalue())
144+
self.assertEqual(logJson.get("timestamp"), "2017-07-14T02:40:00+00:00")
145+
134146
def testJsonCustomDefault(self):
135147
def custom(o):
136148
return "very custom"

0 commit comments

Comments
 (0)