python - 子类化 logging.Formatter 更改 logging.Formatter 的默认行为

标签 python class python-3.x logging subclass

我向我的记录器添加了两个具有不同格式化程序的处理程序。第一个需要继承 logging.Formatter 来进行自定义格式化。默认格式化程序将满足第二个处理程序的需要。

假设第一个格式化程序只是从消息中删除换行符。以下脚本说明了看似奇怪的行为:

import logging

logger = logging.getLogger(__name__)

class CustomFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def format(self, record):
        record.msg = record.msg.strip().replace('\n', ' ')
        return super().format(record)

h1 = logging.StreamHandler()
formatter1 = CustomFormatter(fmt=None, datefmt=None)
h1.setFormatter(formatter1)
logger.addHandler(h1)

h2 = logging.StreamHandler()
formatter2 = logging.Formatter(fmt=None, datefmt=None)
h2.setFormatter(formatter2)
logger.addHandler(h2)

logger.warning('string with\nmultiple lines')

输出如下:

string with multiple lines
string with multiple lines

我期望的是:

string with multiple lines
string with 
multiple lines

第二个格式化程序不应该实现 CustomFormatter 的行为,但它确实实现了。当我颠倒处理程序添加到记录器的顺序时,这不会发生。

除非我误解了子类化,否则不应通过重写子类中的方法来改 rebase 类的行为。当我覆盖 logging.Formatter 以外的类的方法时,这似乎不是问题。

这是日志记录模块中的错误,还是我在这里遗漏了什么?

最佳答案

这条线是你的失败:

record.msg = record.msg.strip().replace('\n', ' ')

您将已清理的字符串重新分配给附加到记录器的所有剩余处理程序/格式化程序所使用的记录。复制记录并起作用:

import logging
from copy import copy

logger = logging.getLogger(__name__)

class CustomFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def format(self, record):
        record = copy(record)
        record.msg = record.msg.strip().replace('\n', ' ')
        return super().format(record)

h1 = logging.StreamHandler()
formatter1 = CustomFormatter(fmt=None, datefmt=None)
h1.setFormatter(formatter1)
logger.addHandler(h1)

h2 = logging.StreamHandler()
formatter2 = logging.Formatter(fmt=None, datefmt=None)
h2.setFormatter(formatter2)
logger.addHandler(h2)

logger.warning('string with\nmultiple lines')

输出

string with multiple lines
string with
multiple lines

关于python - 子类化 logging.Formatter 更改 logging.Formatter 的默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37900521/

相关文章:

python - 使用 selenium 和 python 在 Linkedin 上添加连接

java - 如何添加类的匿名实例作为 ActionListener

c++ - 类和文件阅读

HTML <a> 标签比指定宽度宽

python - 从请求中获取字节响应

Python Pycharm : Plot gets Coarse When Zoomed in

python - 在 IPython/Jupyter Notebooks 中显示行号

python - 使用 tkinter 变量查询 MySQL 数据库

python - 在 Pandas 数据框中使用 pyproj 在投影之间进行转换

python - 如何找到 python 模块包含的 DLL 文件的完整路径?