Python日志:如何在日志配置文件的格式字符串中表示换行?

12 投票
6 回答
11617 浏览
提问于 2025-04-17 09:34

我正在通过一个文件来配置我的Python日志记录(可以参考这个链接:http://www.python.org/doc//current/library/logging.html#configuration-file-format)。

在那个页面的示例中,我的配置文件里有一个格式化器,内容是这样的:

[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter

我想在指定格式化器的“format”字符串中加入换行符,该怎么做呢?使用 \n 或者 \\n 都不行(比如 format=F1\n%(asctime)s %(levelname)s %(message)s 这样写是无效的)。谢谢!

6 个回答

0

我觉得最好的办法是使用自定义的格式化器(而不是 logging.Formatter)……这里有 logging.Formatter.format 的源代码供你参考:

def format(self, record):
    record.message = record.getMessage()
    if string.find(self._fmt,"%(asctime)") >= 0:
        record.asctime = self.formatTime(record, self.datefmt)
    s = self._fmt % record.__dict__
    if record.exc_info:
        # Cache the traceback text to avoid converting it multiple times
        # (it's constant anyway)
        if not record.exc_text:
            record.exc_text = self.formatException(record.exc_info)
    if record.exc_text:
        if s[-1:] != "\n":
            s = s + "\n"
        s = s + record.exc_text
    return s

我很清楚,如果 self._fmt 是从一个文本文件中读取的(单行),那么就不可能进行任何转义。也许你可以从 logging.Formatter 继承,重写这个方法,把第4行替换成类似下面的内容:

s = self._fmt.replace('\\n', '\n') % record.__dict__

或者如果你想让其他东西也进行转义,可以用更通用的方法。

补充一下:你也可以在 init 方法中做这件事,只需要做一次(而不是每次格式化消息时都做)。不过正如其他人已经指出的,ConfigParser 支持多行,所以其实没必要走这条路……

7

日志配置文件是基于 ConfigParser 模块的。在这里,你可以这样来解决问题:

[formatter_form01]
format=F1
   %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
9

logging.config模块可以读取配置文件,这个过程是通过ConfigParser来实现的,它支持多行的值。

因此,你可以像这样指定你的format字符串:

[formatter_form01]
format=F1
    %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter

多行的值可以通过在后面的行前面加空格或制表符来继续(一个或多个空格或制表符都算作缩进)。

撰写回答