Python 将ExtendedInterpolation与Logging.Config.FileConfig一起使用
我正在寻找一种方法,在将ini文件加载到Logging.config.FileConfig时,使用configparser库中的ExtendedInterpolation功能 因此,如果我有一个ini文件,看起来像这样:Python 将ExtendedInterpolation与Logging.Config.FileConfig一起使用,python,logging,interpolation,Python,Logging,Interpolation,我正在寻找一种方法,在将ini文件加载到Logging.config.FileConfig时,使用configparser库中的ExtendedInterpolation功能 因此,如果我有一个ini文件,看起来像这样: [logSettings] eventlogs=application logfilepath=C:\Programs\dk_test\results\dklog_009.log levelvalue=10 [formatters] keys=dkeventFmt,dklo
[logSettings]
eventlogs=application
logfilepath=C:\Programs\dk_test\results\dklog_009.log
levelvalue=10
[formatters]
keys=dkeventFmt,dklogFmt
[handlers]
keys=dklogHandler
[handler_dklogHandler]
class=FileHandler
level=${logSettings:levelvalue}
formatter=dklogFmt
args=(${logSettings:logfilepath}, 'w')
[logger_dklog]
level=${logSettings:levelvalue}
handlers=dklogHandler
tmpConfigDict = {}
tmpConfig = ConfigParser(allow_no_value = True,
interpolation = ExtendedInterpolation())
for path in configPaths:
tmpConfig.read(path)
#Iterate over options and use "get()" to execute the Interpolation
for sec in tmpConfig.sections():
tmpConfigDict[sec] = {}
for opt, _ in tmpConfig[sec].items():
tmpConfigDict[sec][opt] = cleanValue(tmpConfig.get(sec, opt))
#Finished getting values. Write the dict to the configparser
tmpConfig.read_dict(tmpConfigDict)
#Open the file handle and close it when done
with open(pathToTmpFile, 'w') as fp:
tmpConfig.write(fp, space_around_delimiters = False)
如您所见,我使用${…}符号引用不同部分中的值,从而遵循扩展插值语法。当调用文件如sologging.config.fileConfig(filepath)
时,模块内的评估总是失败。特别是在[handler\dklogHandler]
部分中评估args选项
有没有办法绕过这个问题?谢谢
注意:使用Python 3.2决定对文件使用强制插值,并将结果保存到另一个临时文件。我使用临时文件进行日志配置 函数如下所示:
[logSettings]
eventlogs=application
logfilepath=C:\Programs\dk_test\results\dklog_009.log
levelvalue=10
[formatters]
keys=dkeventFmt,dklogFmt
[handlers]
keys=dklogHandler
[handler_dklogHandler]
class=FileHandler
level=${logSettings:levelvalue}
formatter=dklogFmt
args=(${logSettings:logfilepath}, 'w')
[logger_dklog]
level=${logSettings:levelvalue}
handlers=dklogHandler
tmpConfigDict = {}
tmpConfig = ConfigParser(allow_no_value = True,
interpolation = ExtendedInterpolation())
for path in configPaths:
tmpConfig.read(path)
#Iterate over options and use "get()" to execute the Interpolation
for sec in tmpConfig.sections():
tmpConfigDict[sec] = {}
for opt, _ in tmpConfig[sec].items():
tmpConfigDict[sec][opt] = cleanValue(tmpConfig.get(sec, opt))
#Finished getting values. Write the dict to the configparser
tmpConfig.read_dict(tmpConfigDict)
#Open the file handle and close it when done
with open(pathToTmpFile, 'w') as fp:
tmpConfig.write(fp, space_around_delimiters = False)
请注意,这不是
ExtendedInterpolation
的问题。(因此标题具有误导性。)默认的BasicInterpolation
也会出现这种情况。相反,这是一个使用ConfigParser
和任何值插值以及logging.fileConfig
的问题。我想这是一个解决方案,但肯定不能令人满意。