我正在从文件配置我的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
如何在指定格式化程序的“格式”字符串中添加换行符?也不 \n
也不 \\n
工作(例如 format=F1\n%(asctime)s %(levelname)s %(message)s
不起作用)。谢谢
该 logging.config
模块读取配置文件 ConfigParser
,它支持多行值。
所以你可以指定你的 format
像这样的字符串:
[formatter_form01]
format=F1
%(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
通过缩进以下行来继续多行值(一个或多个空格或制表符计为缩进)。
日志配置文件基于 ConfigParser
模块。在那里你会发现你可以像这样解决它:
[formatter_form01]
format=F1
%(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
我最好的选择是使用自定义格式化程序(而不是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__
或者更通用的东西,如果你想要逃避其他东西。
编辑:或者,您可以在 在里面 方法,一次(而不是每次格式化消息)。但正如其他人已经指出的那样,ConfigParser支持多行,所以不需要走这条路......
这可能是一种简单的方法:
import logging
logformat = """%(asctime)s ... here you get a new line
... %(thread)d .... here you get another new line
%(message)s"""
logging.basicConfig(format=logformat, level=logging.DEBUG)
我测试过,上面的设置为每个日志消息提供了两个新行,如代码中所示。注意: %(asctime)s
这样的事情是python日志格式化字符串。
import logging
logformat = "%(asctime)s %(message)s\n\r"
logging.basicConfig(level=logging.DEBUG, format=logformat,filename='debug.log', filemode='w')
logging.debug (Your String here)
文件中的调试文本将用新行写入。