Python日志:如何在日志配置文件中以格式字符串表示换行符?
我正在从一个文件配置Python日志(请参阅) 从该页面的示例中,我在配置文件中有一个格式化程序,如下所示:Python日志:如何在日志配置文件中以格式字符串表示换行符?,python,logging,config,newline,Python,Logging,Config,Newline,我正在从一个文件配置Python日志(请参阅) 从该页面的示例中,我在配置文件中有一个格式化程序,如下所示: [formatter_form01] format=F1 %(asctime)s %(levelname)s %(message)s datefmt= class=logging.Formatter 如何在指定格式化程序的“格式”字符串中添加换行符?\n和\\n都不起作用(例如格式=F1\n%(astime)s%(levelname)s%(message)s不起作用)。谢谢我的最佳选择
[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
如何在指定格式化程序的“格式”字符串中添加换行符?
\n
和\\n
都不起作用(例如格式=F1\n%(astime)s%(levelname)s%(message)s
不起作用)。谢谢我的最佳选择是使用自定义格式化程序(而不是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.\u fmt是从文本文件(单行)读取的,那么任何类型的转义都是不可能的。也许您可以从logging.Formatter扩展,重写此方法并用第4行替换如下内容:
s = self._fmt.replace('\\n', '\n') % record.__dict__
或者更一般的,如果你想逃避其他事情的话
编辑:或者,您可以在init方法中执行一次(而不是每次格式化消息时)。但是正如其他人已经指出的那样,ConfigParser支持多行,因此不需要走这条路线。
logging.config
模块使用读取配置文件,它支持多行值
因此,您可以像下面这样指定格式字符串:
[formatter_form01]
format=F1
%(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
[formatter_form01]
format=F1
%(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
通过缩进以下行(一个或多个空格或制表符计为缩进)继续多行值。日志配置文件基于模块。你会发现你可以这样解决它:
[formatter_form01]
format=F1
%(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
[formatter_form01]
format=F1
%(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
这可能是一个简单的方法:
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)
文件中的调试文本将用新行写入。只需在basicConfig函数的结束撇号之前添加“\n”
logging.basicConfig(level=logging.DEBUG, format=' %(levelname)s - %(message)s\n')
日志记录中的新行?请不要这样做。日志文件将很难grep。@fabrizioM True,但这与这个问题无关。