You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Each handler added with ``serialize=True`` will create messages by converting the logging record to a valid JSON string. Depending on the sink for which the messages are intended, it may be useful to make changes to the generated string. Instead of using the ``serialize`` parameter, you can implement your own serialization function and use it directly in your sink::
If you need to send structured logs to a file (or any kind of sink in general), a similar result can be obtained by using a custom ``format`` function::
318
+
319
+
def formatter(record):
320
+
# Note that this function returns the string to be formatted, not the actual message to be logged
321
+
record["extra"]["serialized"] = serialize(record)
322
+
return "{extra[serialized]}\n"
323
+
324
+
logger.add("file.log", format=formatter)
325
+
326
+
327
+
You can also use |patch| for this, so the serialization function will be called only once in case you want to use it in multiple sinks::
328
+
329
+
def patching(record):
330
+
record["extra"]["serialized"] = serialize(record)
331
+
332
+
logger = logger.patch(patching)
333
+
334
+
# Note that if "format" is not a function, possible exception will be appended to the message
0 commit comments