Skip to content

Commit fa18834

Browse files
committed
Cache LogRecord.getMessage() the first time the message is formatted
This improves performance in cases where multiple `logging.Formatter`s are used when logging objects with expensive `__str__`/`__repr__` functions.
1 parent b430e92 commit fa18834

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

Lib/logging/__init__.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,7 @@ def __init__(self, name, level, pathname, lineno,
303303
ct = time.time_ns()
304304
self.name = name
305305
self.msg = msg
306+
self.message = None
306307
#
307308
# The following statement allows passing of a dictionary as a sole
308309
# argument, so that you can do something like
@@ -395,10 +396,13 @@ def getMessage(self):
395396
Return the message for this LogRecord after merging any user-supplied
396397
arguments with the message.
397398
"""
398-
msg = str(self.msg)
399-
if self.args:
400-
msg = msg % self.args
401-
return msg
399+
if self.message is None:
400+
msg = str(self.msg)
401+
if self.args:
402+
msg = msg % self.args
403+
self.message = msg
404+
405+
return self.message
402406

403407
#
404408
# Determine which class to use when instantiating log records.
@@ -708,6 +712,8 @@ def format(self, record):
708712
called to format the event time. If there is exception information,
709713
it is formatted using formatException() and appended to the message.
710714
"""
715+
# note: LogRecord.getMessage() will set record.message already but
716+
# custom LogRecord objects may not so it's assigned here anyway
711717
record.message = record.getMessage()
712718
if self.usesTime():
713719
record.asctime = self.formatTime(record, self.datefmt)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Cache LogRecord.getMessage() the first time the message is formatted. Patch
2+
by Carey Metcalfe.

0 commit comments

Comments
 (0)