Python logging file config KeyError: 'formatters'

偶尔善良 提交于 2019-12-03 04:45:32

I had this issue because Python couldn't find my config file, though you would never know it by the error message. Apparently it does not look for the config file relative to the file in which the code is running, but rather relative to the current working directory (which you can get from os.getcwd()). I used the following code to initialize the logger. The log.config file is in the same directory as the file running this code:

from os import path
log_file_path = path.join(path.dirname(path.abspath(__file__)), 'log.config')
logging.config.fileConfig(log_file_path)

Try to replace

logging.config.fileConfig('../logging.conf', disable_existing_loggers=False)

with this

logging.config.fileConfig('logging.conf', disable_existing_loggers=False)

Not sure, but probably your logging.conf is in your current working directory, and with the .. the file cannot be found.

Steven Chen

d512 was correct. And when running the code and based on the PYTHONPATH, Python treats your project root directory as the 'current path' no matter where is your running file located. So another way is to add the relative path either as following:

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

or relative to the current file:

LOGGING_CONFIG = Path(__file__).parent / 'logging.conf'
...
logging.config.fileConfig(LOGGING_CONFIG)

Hope it helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!