Skip to content

Commit 45726ab

Browse files
fix: python2 json dumps UnicodeDecodeError
1 parent 6e57a8b commit 45726ab

File tree

3 files changed

+36
-13
lines changed

3 files changed

+36
-13
lines changed

jsonformatter/jsonformatter.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def usesTime(self):
3737
return self._fmt.find(self.asctime_search) >= 0
3838

3939
def format(self, record):
40-
return str(self._fmt) % record.__dict__
40+
return self._fmt % record.__dict__
4141

4242

4343
class StrFormatStyle(PercentStyle):
@@ -46,7 +46,7 @@ class StrFormatStyle(PercentStyle):
4646
asctime_search = '{asctime'
4747

4848
def format(self, record):
49-
return str(self._fmt).format(**record.__dict__)
49+
return self._fmt.format(**record.__dict__)
5050

5151

5252
class StringTemplateStyle(PercentStyle):
@@ -58,7 +58,7 @@ def __init__(self, fmt):
5858
PercentStyle.__init__(self, fmt)
5959
self._tpl = {}
6060
for _, v in fmt.items():
61-
self._tpl[v] = Template(str(v))
61+
self._tpl[v] = Template(v)
6262

6363
def usesTime(self):
6464
fmt = self._fmt
@@ -220,6 +220,7 @@ def __init__(self, fmt=BASIC_FORMAT, datefmt=None, style='%', record_custom_attr
220220
self.cls = cls
221221
self.indent = indent
222222
self.separators = separators
223+
self.encoding = encoding
223224
self.default = default
224225
self.sort_keys = sort_keys
225226
self.kw = kw
@@ -262,10 +263,10 @@ def formatMessage(self, record):
262263
def format(self, record):
263264
result = dictionary()
264265

265-
# store `record` origin attributes start
266+
# store `record` origin attributes, prevent other formatter use record error start
266267
_msg, _args = record.msg, record.args
267268
record.msg, record.args = '', tuple()
268-
# store `record` origin attributes end
269+
# store `record` origin attributes, prevent other formatter use record error end
269270

270271
self.setRecordMessage(record, _msg, _args)
271272

@@ -274,6 +275,13 @@ def format(self, record):
274275
if self.record_custom_attrs:
275276
self.setRecordCustomAttrs(record)
276277

278+
# compatible python2 start
279+
if sys.version_info < (3, 0):
280+
for k, v in record.__dict__.items():
281+
if isinstance(v, str):
282+
record.__dict__.update({k: v.decode(self.encoding)})
283+
# compatible python2 end
284+
277285
for k, v in self.json_fmt.items():
278286
# this is for keeping `record` attribute `type`
279287
if v in record.__dict__:
@@ -284,8 +292,8 @@ def format(self, record):
284292
result[k] = self.formatMessage(record)
285293
self._style._fmt = ''
286294

287-
# apply `record` origin attributes start
295+
# apply `record` origin attributes, prevent other formatter use record error start
288296
record.msg, record.args = _msg, _args
289-
# apply `record` origin attributes end
297+
# apply `record` origin attributes, prevent other formatter use record error end
290298

291299
return json.dumps(result, skipkeys=self.skipkeys, ensure_ascii=self.ensure_ascii, check_circular=self.check_circular, allow_nan=self.allow_nan, cls=self.cls, indent=self.indent, separators=self.separators, default=self.default, sort_keys=self.sort_keys, **self.kw)

setup.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,28 @@
88
Github: https://github.com/yourname
99
Description: setup.py
1010
"""
11-
11+
import sys
1212
from setuptools import setup
1313

14+
long_description = ''
15+
16+
try:
17+
if 'win' in sys.platform and sys.version_info >= (3, 0):
18+
with open('README.md', encoding='utf-8') as r:
19+
long_description = r.read()
20+
else:
21+
with open('README.md') as r:
22+
long_description = r.read()
23+
except Exception as e:
24+
pass
25+
1426
setup(
1527
name='jsonformatter',
16-
version='0.2.2',
28+
version='0.2.3',
1729
description=(
1830
'Python log in json format.'
1931
),
20-
long_description=open('README.md').read(),
32+
long_description=long_description,
2133
long_description_content_type="text/markdown",
2234
platforms=["all"],
2335
classifiers=[

test/test.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,8 @@ def test_percent_style_unicode(self):
145145
root = logging.getLogger()
146146
root.setLevel(logging.INFO)
147147

148-
formatter = JsonFormatter("""{"log":"%(message)s"}""", style="%")
148+
formatter = JsonFormatter(
149+
"""{"log":"%(message)s"}""", style="%", ensure_ascii=False)
149150

150151
sh = logging.StreamHandler()
151152
sh.setFormatter(formatter)
@@ -158,7 +159,8 @@ def test_format_style_unicode(self):
158159
root = logging.getLogger()
159160
root.setLevel(logging.INFO)
160161

161-
formatter = JsonFormatter("""{"log":"{message}"}""", style="{")
162+
formatter = JsonFormatter(
163+
"""{"log":"{message}"}""", style="{", ensure_ascii=False)
162164

163165
sh = logging.StreamHandler()
164166
sh.setFormatter(formatter)
@@ -171,7 +173,8 @@ def test_template_style_unicode(self):
171173
root = logging.getLogger()
172174
root.setLevel(logging.INFO)
173175

174-
formatter = JsonFormatter("""{"log":"${message}"}""", style="$")
176+
formatter = JsonFormatter(
177+
"""{"log":"${message}"}""", style="$", ensure_ascii=False)
175178

176179
sh = logging.StreamHandler()
177180
sh.setFormatter(formatter)

0 commit comments

Comments
 (0)