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


  在第959行的文件“ /usr/local/lib/python3.6/configparser.py”
  getitem引发KeyError(key)KeyError:“格式化程序”


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脚本加载配置时,我遇到了类似的问题。我发现的是:

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")

关于python - python3.6:KeyError:“格式程序”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47636747/

10-10 22:34