Skip to content

Commit

Permalink
Support pickling of LogRecords that use brace-style formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
pR0Ps committed Jun 13, 2024
1 parent a29a4ab commit 38f9ebc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions bracelogger.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ def _get_message(record):


def _handle_wrap(fcn):
"""Wrap logging.Handler.handle to use _getMessage"""
"""Wrap logging.Handler.handle to use _get_message"""

@functools.wraps(fcn)
def handle(record):
record.getMessage = types.MethodType(_get_message, record)
record.getMessage = functools.partial(_get_message, record)
return fcn(record)

return handle
Expand Down
23 changes: 23 additions & 0 deletions tests/test_bracelogger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python

import logging
import pickle
import sys

import bracelogger
Expand Down Expand Up @@ -118,3 +119,25 @@ def test_all_levels(caplog):
record = next(x for x in caplog.records if x.args[0] == level)
assert record.msg == TEMPLATE
assert record.message == TEMPLATE.format(*record.args)


def test_pickle_logrecord(caplog):
"""Test that the modified LogRecords can be [de]serialized using the pickle module"""
caplog.set_level(logging.INFO)

bl = bracelogger.get_logger("logger6")
sl = logging.getLogger("logger7")

data = {"a": 1, "b": 2}
TEMPLATES = ("a:{0[a]}, b:{0[b]}", "a:{a}, b:{b}", "a:%(a)s, b:%(b)s")

bl.info(TEMPLATES[0], data)
bl.info(TEMPLATES[1], data)
sl.info(TEMPLATES[2], data)

for r, tmpl in zip(caplog.records, TEMPLATES):
new = pickle.loads(pickle.dumps(r))
assert new.levelno == r.levelno == logging.INFO
assert new.args == r.args == data
assert new.msg == r.msg == tmpl
assert new.getMessage() == new.message == r.message == "a:1, b:2"

0 comments on commit 38f9ebc

Please sign in to comment.