Python日志记录:在配置文件中指定日志格式化程序的转换器属性
我希望日志文件中的所有时间戳都是UTC时间戳。当通过代码指定时,按如下方式执行:Python日志记录:在配置文件中指定日志格式化程序的转换器属性,python,logging,config,converter,formatter,Python,Logging,Config,Converter,Formatter,我希望日志文件中的所有时间戳都是UTC时间戳。当通过代码指定时,按如下方式执行: import logging import time myHandler = logging.FileHandler('mylogfile.log', 'a') formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)-15s:%(lineno)4s: %(message)-80s') formatter.converter = time
import logging
import time
myHandler = logging.FileHandler('mylogfile.log', 'a')
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)-15s:%(lineno)4s: %(message)-80s')
formatter.converter = time.gmtime
myHandler.setFormatter(formatter)
myLogger = logging.getLogger('MyApp')
myLogger.addHandler(myHandler)
myLogger.setLevel(logging.DEBUG)
myLogger.info('here we are')
我想从上面的“代码内”配置转移到基于配置文件的机制
以下是格式化程序的配置文件部分:
[handler_MyLogHandler]
args=("mylogfile.log", "a",)
class=FileHandler
level=DEBUG
formatter=simpleFormatter
现在,如何在上面的部分中指定转换器属性(time.gmtime)
编辑:加载上述配置文件,因此:
logging.config.fileConfig('myLogConfig.conf')
遗憾的是,除了使用配置文件(例如
class UTCFormatter(logging.Formatter):
converter = time.gmtime
然后在配置中使用
UTC格式。这里Vinay的解决方案应用于logging.basicConfig:
import logging
import time
logging.basicConfig(filename='junk.log', level=logging.DEBUG, format='%(asctime)s: %(levelname)s:%(message)s')
logging.Formatter.converter = time.gmtime
logging.info('A message.')
什么解析配置文件?很明显,这个问题遗漏了一些东西。谢谢你指出这一点。我已经将细节添加到qn中。我更新了您的代码示例,使其实际运行并记录。始终提供完整的代码示例。您的配置不完整;这里是我在加载它时遇到的异常:ConfigParser.NoSectionError:No部分:“formatters”