自2.5版以来的日志记录更改

时间:2012-01-05 21:31:58

标签: python logging

我一直在使用python日志记录模块已经有一段时间了,但是最近,在测试与旧python版本的兼容性时遇到了一些麻烦:

Traceback (most recent call last):
  File "hunter.py", line 16, in <module>
    logging.config.fileConfig("logging.conf")
  File "/usr/lib/python2.5/logging/config.py", line 85, in fileConfig
    _install_loggers(cp, handlers)
  File "/usr/lib/python2.5/logging/config.py", line 229, in _install_loggers
    logger.addHandler(handlers[string.strip(hand)])
KeyError: 'hunterFileHandler'

使用以下配置文件(仅限重要部分):

[loggers]
keys=root,hunter

[handlers]
keys=consoleHandler, hunterFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_hunter]
level=DEBUG
handlers=consoleHandler, hunterFileHandler
qualname=hunter
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_hunterFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("logs/hunter.log", "a", 0, 10,)

[formatter_simpleFormatter]
format=%(asctime)s:[%(name)s][%(levelname)5s] %(message)s
datefmt=

是否有一种简单的方法可以使配置向后兼容而不会复制大部分内容?

1 个答案:

答案 0 :(得分:0)

您的问题很可能是由此行中的空格引起的:

keys=consoleHandler, hunterFileHandler
                    ^

由于2.5中存在错误,系统不会跳过前导空格,并且您获得KeyError,因为密钥错误地设置为" hunterFileHandler"。如果您将此行更改为

keys=consoleHandler,hunterFileHandler

然后文件应该正确加载。

但是,你应该注意到在2.5和2.6中修复了几个错误,所以你可能会被其中一个(除了我提到过的那个)咬了。请参阅jcollado对您问题的评论。