Skip to main content
 首页 » 编程设计

使用配置文件记录 Python 3.2 导致 KeyError : 'formatters' on Raspbian

2025年05月04日89zhujiabin

我为我的 Python 应用程序配备了日志记录功能,它在我的 Windows 系统上使用 Python 3.4 完美运行。但是当我使用 Raspbian 和 Python 3.2 在我的 Raspberry Pi 上部署应用程序时,我收到以下错误:

Traceback (most recent call last): 
  File "aurora/aurora_websocket.py", line 265, in <module> 
    logging.config.fileConfig('logging.conf') 
  File "/usr/lib/python3.2/logging/config.py", line 70, in fileConfig 
    formatters = _create_formatters(cp) 
  File "/usr/lib/python3.2/logging/config.py", line 106, in _create_formatters 
    flist = cp["formatters"]["keys"] 
  File "/usr/lib/python3.2/configparser.py", line 941, in __getitem__ 
    raise KeyError(key) 
KeyError: 'formatters' 

logging.conf 文件(以不带 BOM 的 UTF-8 编码):

[loggers] 
keys=root,simpleExample 
 
[handlers] 
keys=screen 
 
[formatters] 
keys=simple,complex 
 
[logger_root] 
level=NOTSET 
handlers=screen 
 
[logger_simpleExample] 
level=DEBUG 
handlers=screen 
qualname=simpleExample 
propagate=0 
 
[handler_screen] 
class=StreamHandler 
level=DEBUG 
formatter=complex 
args=(sys.stdout,) 
 
[formatter_simple] 
format=%(asctime)s - %(levelname)s - %(message)s 
datefmt= 
 
[formatter_complex] 
format=%(asctime)s - %(levelname)-8s - <%(module)s : %(lineno)d> - %(message)s 
datefmt= 

日志配置在一个简单的一行中加载:

logging.config.fileConfig('logging.conf') 

我在这里不知所措,因为如上所述,我的应用程序在 Windows 上运行良好,但在 RPi 上运行失败。

请您参考如下方法:

好吧,这并没有持续多久...事实证明,我一直在 RPi 上从不同的工作目录运行我的应用程序。因此,logging.conf 文件的文件路径相对于不同的工作目录被错误地解释。不幸的是,日志库会尝试继续处理不存在的文件,并且在这种情况下不会抛出有用的异常。