bsh*_*nks 11 python logging config newline
我正在从文件配置我的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
Run Code Online (Sandbox Code Playgroud)
如何在指定格式化程序的"格式"字符串中添加换行符?既不工作\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
Run Code Online (Sandbox Code Playgroud)
通过缩进以下行来继续多行值(一个或多个空格或制表符计为缩进).
日志记录配置文件基于该ConfigParser模块.在那里你会发现你可以像这样解决它:
[formatter_form01]
format=F1
%(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
Run Code Online (Sandbox Code Playgroud)
我最好的选择是使用自定义格式化程序(而不是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
Run Code Online (Sandbox Code Playgroud)
我很清楚,如果从文本文件(单行)读取 self._fmt ,则不可能进行任何类型的转义。也许您可以从logging.Formatter扩展,重写此方法并将第四行替换为以下内容:
s = self._fmt.replace('\\n', '\n') % record.__dict__
Run Code Online (Sandbox Code Playgroud)
或者更一般的东西,如果你还想转义其他东西。
编辑:或者,您可以在init方法中执行一次(而不是每次格式化消息时)。但正如其他人已经指出的那样,ConfigParser 支持多行,所以不需要走这条路......