Skip to main content
 首页 » 编程设计

python之自 2.5 版以来日志记录的变化

2025年05月04日11unruledboy

我使用 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= 

有没有一种简单的方法可以使配置向后兼容而无需复制大部分配置?

请您参考如下方法:

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

keys=consoleHandler, hunterFileHandler 
                    ^ 

由于 2.5 中的错误,不会跳过前导空格,并且您会收到 KeyError,因为 key 被错误地设置为 "hunterFileHandler"。如果将此行更改为

keys=consoleHandler,hunterFileHandler 

然后文件应该正确加载。

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