Skip to content

Commit 009c4b3

Browse files
committed
Document usage of custom "serialize" function (#278)
1 parent 1d4c551 commit 009c4b3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/resources/recipes.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,44 @@ However, it should be noted that it's not possible to chain |opt| calls, using t
298298
logger.opt(raw=True).info("It <green>still</> works!\n")
299299

300300

301+
Serializing log messages using a custom function
302+
------------------------------------------------
303+
304+
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::
305+
306+
def serialize(record):
307+
subset = {"timestamp": record["time"].timestamp(), "message": record["message"]}
308+
return json.dumps(subset)
309+
310+
def sink(message):
311+
serialized = serialize(message.record)
312+
print(serialized)
313+
314+
logger.add(sink)
315+
316+
317+
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
335+
logger.add(sys.stderr, format="{extra[serialized]}")
336+
logger.add("file.log", format="{extra[serialized]}")
337+
338+
301339
Dynamically formatting messages to properly align values with padding
302340
---------------------------------------------------------------------
303341

0 commit comments

Comments
 (0)