Mayil-AI-Sandbox / loguru-Jan2023

MIT License
0 stars 0 forks source link

print logs in JSON format, causing an error (hashtag635) #82

Closed vikramsubramanian closed 3 weeks ago

vikramsubramanian commented 3 weeks ago
import json

from loguru import logger

logger.add("runtime.log")
logger.add("special.log", filter=lambda record: record["extra"].get("name") == "special")
special_logger = logger.bind(name="special")

dct = {"message": "xxx"}
text = json.dumps(dct, ensure_ascii=False)
logger.info(text, name="special")  hashtag KeyError: '"message"'
special_logger.info(text)  hashtag right

logger.info("xxx", name="special") can achieve the effect, but when print json format string by this way will causing an KeyError.

vikramsubramanian commented 3 weeks ago

When using the logger, Loguru will try to format the message according to provided arguments. The logger was initialized intended to be used this way:

value = 42
logger.info("Some message with value: {}", value)

Internally, it roughly calls:

message.format(*args, **kwargs)

In your case, due to text begin a JSON-serialized message, the formatting raises an exception because it wasn't intended to be formatted but Loguru isn't aware of that.

As a workaround, you can use bind() to structure your message this way:

logger.bind(name="special").info(text)

In future version, the automatic formatting will likely be removed in favor of f-strings.