【发布时间】: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