Open NobleMathews opened 2 months ago
To address the issue described, you can implement the following changes:
formatter
function to check if the message
is a dict
or list
and format it using json.dumps
with indentation if it is.patcher
function that modifies the record
to include the indentation level from logger_indentation
and applies it to the message
.logger.patch(patcher)
to apply the indentation to all messages.with indent_logs(4):
with logger.bind(indent=4)
to set the indentation level using bind()
instead of a context manager.patcher
function to read the indentation level from record["extra"].get("indent", 0)
and apply it to the message
.Here is a sample implementation:
import json
from loguru import logger
from contextvars import ContextVar
logger_indentation = ContextVar("logger_indentation", default=0)
def formatter(record):
message = record["message"]
if isinstance(message, (dict, list)):
# Format message as JSON with indentation
message = json.dumps(message, indent=4)
record["message"] = message
return "{time} - {level} - {message}\n"
def patcher(record):
base_indent = logger_indentation.get()
indent = record["extra"].get("indent", 0)
total_indent = ' ' * (base_indent + indent)
record["message"] = total_indent + record["message"].replace('\n', '\n' + total_indent)
logger.configure(handlers=[{"sink": sys.stderr, "format": formatter}])
logger.patch(patcher)
# Usage example
logger.bind(indent=4).info("Indented message")
This code snippet assumes that the formatter
function is used to format log messages and that the patcher
function is used to apply indentation. The logger_indentation
context variable is used to keep track of the current indentation level, and the bind()
method is used to set the indentation level for specific log messages.
NONE
search_embedding: 1.3e-07
snippet_processor: 0.13788000000000003
issue_star_creation: 0.03249
issue_star_solver: 0.14106000000000002
bouncer: 0.02975
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()
? 🤔