Closed vikramsubramanian closed 2 months ago
Configure the logger
to use a custom formatter that handles JSON serialization with indentation:
import json
from loguru import logger
def json_formatter(record):
record["extra"]["data"] = json.dumps(record["extra"].get("data", {}), indent=4)
return "{time} - {level} - {message} - {extra[data]}\n"
logger.remove()
logger.add(sys.stderr, format=json_formatter)
Use logger.bind()
to attach the dict
data you want to log:
logger.bind(data={"key": "value"}).info("Log message")
If you want to apply indentation globally without using bind()
every time, you can patch the logger
:
from loguru import logger
def patcher(record):
if isinstance(record["extra"].get("data"), dict):
record["extra"]["data"] = json.dumps(record["extra"]["data"], indent=4)
logger.configure(patcher=patcher)
Then, log your dict
using the extra
parameter:
logger.info("Log message", extra={"data": {"key": "value"}})
Ensure that the extra
parameter is not used for other purposes in your logging calls, as it is now reserved for dict
data that needs to be formatted.
Hey ! 👋 🙂
I've been through quite some "issues" with a similar topic (including which I have also participated in! ) but I thought perhaps a new thread is worth it, instead of reviving a closed one. 😅
hashtag Logging
Lists
&Dicts
Previously, you helped me get to [this]( point:
However, in the above example, I was logging a
str
, and instead, I'd like to log adict
:lists
ordicts
?hashtag Logging with indents
Wrt OP's original query, I'd like to also have indentation, but slightly different.
This was the proposed solution:
And in my use-case, I am doing this:
With output:
But, what I'd preferably like to have is one log statement:
And preferably not having to use a context manager - maybe something similar to using
bind()
? 🤔 )