Open SmartHypercube opened 2 months ago
This looks like a feature, not a bug. Is there any reason to cache this? str
and %
are not expensive operations.
I don't have strong opinion about whether this should be a bug report or a feature request. Please change it if needed.
str
may be expensive, if user uses a custom class for msg
with an expensive __str__
method.%
may also be expensive, for example, when %r
is used with a nested class structure.datetime
object, LogRecord.message
will be more expensive than LogRecord.asctime
, which is currently cached.https://docs.python.org/3/howto/logging-cookbook.html#implementing-structured-logging shows 2 examples involving expensive __str__
methods. That's actually very similar to my use case. Currently, each Handler in my program calls json.dumps
on the same structure repeatedly. I do think it is wasteful and impacting latency.
I'm wondering if this would be a breaking change -- could people be relying on getMessage()
to call __str__
every time, or something along those lines?
I think this is a breaking change, we may need to discuss it in https://discuss.python.org/
Bug report
Bug description:
logging
currently does not cacheLogRecord.message
: https://github.com/python/cpython/blob/0dcbc8385322ff51f7fc3e586027d880275df4fa/Lib/logging/__init__.py#L391-L401 https://github.com/python/cpython/blob/0dcbc8385322ff51f7fc3e586027d880275df4fa/Lib/logging/__init__.py#L711Since
logging
caches other string-formatting related results such asLogRecord.asctime
andLogRecord.exc_text
, I would like to suggest:LogRecord.getMessage
should checkself.message
first. If it is not computed yet, it should compute the message and set this attribute before returning.Formatter
shouldn't setrecord.message
. It only needs to callLogRecord.getMessage
to get the message.How to reproduce
Expected output
Actual output
CPython versions tested on:
3.12
Operating systems tested on:
Linux