我已在logging.config文件中配置了日志记录。我创建了一个类来访问此配置文件,启用/禁用记录器,并记录一些Info消息。我在所有需要进行日志记录的模块中导入此类。当我尝试登录到文件时,我收到此错误消息。我无法理解这个错误意味着什么。
文件" /usr/local/lib/python3.6/configparser.py",第959行, getitem 引发KeyError(键)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")
答案 0 :(得分: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")