python3.6:KeyError:'formatters'

问题描述 投票:1回答:1

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

文件“ /usr/local/lib/python3.6/configparser.py”,第959行,在getitem引发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")
python python-3.x logging keyerror
1个回答
0
投票

当我尝试从不在项目根目录下的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") 
© www.soinside.com 2019 - 2024. All rights reserved.