python / python/cpython

logging should cache LogRecord.message

未关闭
#122,089 7 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-feature
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

logging currently does not cache LogRecord.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#L711

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
  • gh-134367

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

阅读 Lib/logging/init.py 中所引用的 LogRecord 和 Formatter 位置,然后运行 reproduction 以观察重复的 repr 调用。开始前查看链接的 PR gh-134367。完成的标准是:双 handler 示例调用 repr 一次,同时两个 handler 都生成消息。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
observability
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
30/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。