7

我希望我的日志文件中的所有时间戳都是 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.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')
4

2 回答 2

4

可悲的是,除了使用配置文件之外,没有其他方法可以做到这一点

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

然后UTCFormatter在配置中使用 a 。

于 2012-09-11T17:51:44.927 回答
3

这里将 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.')
于 2013-12-09T23:23:33.897 回答