Skip to content

logging should cache LogRecord.messageΒ #122089

@SmartHypercube

Description

@SmartHypercube

Bug report

Bug description:

logging currently does not cache LogRecord.message:

def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
"""
msg = str(self.msg)
if self.args:
msg = msg % self.args
return msg

record.message = record.getMessage()

Since logging caches other string-formatting related results such as LogRecord.asctime and LogRecord.exc_text, I would like to suggest:

  1. LogRecord.getMessage should check self.message first. If it is not computed yet, it should compute the message and set this attribute before returning.
  2. Formatter shouldn't set record.message. It only needs to call LogRecord.getMessage to get the message.

How to reproduce

import logging

class A:
    def __repr__(self):
        print('repr called')
        return '<A>'

logger = logging.getLogger()
logger.addHandler(logging.StreamHandler())
logger.addHandler(logging.StreamHandler())
logger.error('%r', A())

Expected output

repr called
<A>
<A>

Actual output

repr called
<A>
repr called
<A>

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions