Skip to content

Commit

Permalink
Prevent non-ascii characters to be escaped while logging JSON (#575)
Browse files Browse the repository at this point in the history
Co-authored-by: jiancheng <ye_jiancheng@cn.vobilegroup.com>
Co-authored-by: Delgan <delgan.py@gmail.com>
  • Loading branch information
3 people committed Jan 24, 2022
1 parent d38ced7 commit b02ef7a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Expand Up @@ -3,6 +3,7 @@

- Modify coroutine sink to make it discard log messages when ``loop=None`` and no event loop is running (due to internally using ``asyncio.get_running_loop()`` in place of ``asyncio.get_event_loop()``).
- Remove the possibility to add a coroutine sink with ``enqueue=True`` if ``loop=None`` and no event loop is running.
- Prevent non-ascii characters to be escaped while logging JSON message with ``serialize=True`` (`#574 <https://github.com/Delgan/loguru/pull/575>`_, thanks `@ponponon <https://github.com/ponponon>`_).
- Fix ``flake8`` errors and improve code readability (`#353 <https://github.com/Delgan/loguru/issues/353>`_, thanks `@AndrewYakimets <https://github.com/AndrewYakimets>`_).


Expand Down
2 changes: 1 addition & 1 deletion loguru/_handler.py
Expand Up @@ -257,7 +257,7 @@ def _serialize_record(text, record):
},
}

return json.dumps(serializable, default=str) + "\n"
return json.dumps(serializable, default=str, ensure_ascii=False) + "\n"

def _queued_writer(self):
message = None
Expand Down
16 changes: 15 additions & 1 deletion tests/test_add_option_serialize.py
@@ -1,15 +1,18 @@
import json
import re
import sys

from loguru import logger


class JsonSink:
def __init__(self):
self.message = None
self.dict = None
self.json = None

def write(self, message):
self.message = message
self.dict = message.record
self.json = json.loads(message)

Expand All @@ -23,6 +26,17 @@ def test_serialize():
assert set(sink.dict.keys()) == set(sink.json["record"].keys())


def test_serialize_non_ascii_characters():
sink = JsonSink()
logger.add(sink, format="{level.icon} {message}", serialize=True)
logger.debug("天")
assert re.search(r'"message": "([^\"]+)"', sink.message).group(1) == "天"
assert re.search(r'"text": "([^\"]+)"', sink.message).group(1) == "🐞 天\\n"
assert re.search(r'"icon": "([^\"]+)"', sink.message).group(1) == "🐞"
assert sink.json["text"] == "🐞 天\n"
assert sink.dict["message"] == sink.json["record"]["message"] == "天"


def test_serialize_exception():
sink = JsonSink()
logger.add(sink, format="{message}", serialize=True, catch=False)
Expand Down Expand Up @@ -77,7 +91,7 @@ def test_serialize_exception_none_tuple():
}


def test_serialize_exception_instrance():
def test_serialize_exception_instance():
sink = JsonSink()
logger.add(sink, format="{message}", serialize=True, catch=False)

Expand Down

0 comments on commit b02ef7a

Please sign in to comment.