Open vikramsubramanian opened 7 months ago
formatter
function that can handle JSON serialization of dicts
and lists
for logging.patcher
function to apply indentation based on the logger_indentation
level.logger.bind()
method to attach structured data to logs without a context manager.formatter
and patcher
functions.# Define a formatter function that serializes dicts and lists to JSON
def formatter(record):
message = record["message"]
if isinstance(message, (dict, list)):
# Serialize the message to JSON format
record["message"] = json.dumps(message, indent=logger_indentation.get(default=0))
return "{time} - {level} - {message}\n"
# Define a patcher function that applies indentation
def patcher(record):
indentation = ' ' * logger_indentation.get(default=0)
record["message"] = indentation + record["message"]
# Configure the logger to use the new formatter and patcher
logger.configure(handlers=[{"sink": sys.stderr, "format": formatter, "patch": patcher}])
# Example usage of logger with bound data
logger.bind(data=some_dict).info("Message with data")
logger_indentation
is a ContextVar
that holds the current indentation level.formatter
function should check if the message is a dict
or list
and serialize it to JSON with indentation.patcher
function should prepend spaces to the message based on the current indentation level.formatter
and patcher
to apply these changes to all logged messages.logger.bind()
to attach additional structured data to the log message without using a context manager.
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()
? 🤔 )