【问题标题】:python3.6 : KeyError: 'formatters'python3.6:KeyError:'格式化程序'
【发布时间】:2017-12-04 15:31:50
【问题描述】:

我已经在 logging.config 文件中配置了日志记录。我创建了一个类,我可以在其中访问此配置文件,启用/禁用记录器,并记录一些 Info 消息。我在我需要做一些日志记录的所有模块中导入这个类。当我尝试登录文件时,我收到此错误消息。我无法理解此错误的含义。

文件“/usr/local/lib/python3.6/configparser.py”,第 959 行,在 getitem raise KeyError(key) KeyError: 'formatters'

logging.config
[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=INFO
handlers=fileHandler

[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=('example.log','a')

[formatter_simpleFormatter]
class=logging.Formatter
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

#Log.py
import logging.config
class Monitor(object):

    fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") 
    print (fileName) #prints /usr/local/lib/python3.6/site-packages/myproject-0.0.1-py3.6.egg/MyPackageName/logging.config
    logging.config.fileConfig(fileName)
    logger = logging.getLogger('root') 
    logger.disabled = False

    @staticmethod
    def Log(logMessage):
        Monitor.logger.info(logMessage)

#sub.py
import Monitor
class Example

def simplelog(self,message):
        Monitor.Log("Logging some  message here")
        #call some function here
        Monitor.Log("Logging some other messages here for example")

【问题讨论】:

  • 文件fileName真的存在吗?你的程序真的可以打开它吗?如果我尝试调用 fileconfig 并传入一个不存在的文件,我会看到同样的错误。
  • 是的,文件名确实存在。它放在我有其他模块和配置文件的包下。我应该设置打开和读取文件的权限吗?
  • 我会确保您的程序实际上可以打开并读取该文件 - 例如使用f = open(...); print(f.read()) 进行检查。

标签: python python-3.x logging keyerror


【解决方案1】:

当我尝试从不在项目根目录中的 python 脚本加载配置时,我遇到了类似的问题。我发现:

logging.config.fileConfig 依赖于configparser,并且在使用绝对路径进行初始化时存在问题。尝试相对路径。

替换

    fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") 

有一些类似的东西:

    ## get path tree from project root and replace children from root with ".."
    path_rslv = path.split(path.dirname(path.abspath(__file__)))[1:] 
    fileName = path.join(*[".." for dotdot in range(len(path_rslv)], "logging.config") 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 2011-06-08
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2018-01-12
    相关资源
    最近更新 更多