我已经设置了一个 Python 日志记录器,使用 Python 的 logging 模块。我想将我正在使用的字符串与 logging Formatter 对象一起存储在配置文件中,并使用 ConfigParser 模块。格式化字符串存储在设置字典中,该字典位于另一个处理配置文件的文件中。我的问题是,Python 仍然尝试格式化文件,并在读取所有 logging 模块特定的格式化标志时失败。
{
"log_level":logging.debug,
"log_name":"C:\\Temp\\logfile.log",
"format_string":
"%(asctime)s %(levelname)s: %(module)s, line %(lineno)d - %(message)s"
}
我的问题很简单:如何在其他地方保持格式化功能的前提下禁用此处的格式化功能。我的最初反应是大量使用反斜杠来转义各种百分号符号,但这当然会永久性地破坏格式化,以至于即使在我需要它时也无法正常工作。
我还应该提到,在评论中已经提到过,ConfigParser执行一些内部插值,导致了此类问题。以下是我的回溯信息:
Traceback (most recent call last):
File "initialconfig.py", line 52, in <module>
"%(asctime)s %(levelname)s: %(module)s, line %(lineno)d - %(message)s"
File "initialconfig.py", line 31, in add_settings
self.set(section_name, setting_name, default_value)
File "C:\Python26\lib\ConfigParser.py", line 668, in set
"position %d" % (value, m.start()))
ValueError: invalid interpolation syntax in '%(asctime)s %(levelname)s: %(module
)s, line %(lineno)d - %(message)s' at position 10
此外,关于良好的设置文件实践的一般指针也会很有帮助。这是我第一次使用ConfigParser(或记录器)进行重要操作。
提前感谢,多米尼克
%
[或string.substitute()
] 显式地请求时,格式化才会发生。 - Andrew Jaffe