配置文件中的错误:处理程序-Python日志记录

时间:2018-10-12 08:47:10

标签: python python-3.x pycharm

简单的python,它尝试使用文件config写入日志信息

import logging
import logging.config
import os

logging.config.fileConfig('Log_parameters.ini')

log_learn = logging.getLogger('sakthi')

def complex_algorithm(items):
    for i, item in enumerate(items):
        # do some complex algorithm computation
        log_learn.debug('%s iteration, item=%s', i, item)

k = [1,2,3]

complex_algorithm(k)

Log_parameters.ini我正在设置配置文件中的处理程序,格式化程序。

[loggers]
keys = sakthi
[handlers]
keys = handle1
[formatters]
keys = simpleformatter

[logger_sakthi]
level = DEBUG
handlers = handle1
qualname = compiler.parser
propogate = 0

[logger_handle1]
class = FileHandler
level = DEBUG
formatter = simpleformatter
args= ('Configg_log','w')

[formatter_simpleformatter]
format=F1 %(asctime)s - %(name)s - %(levelname)s - %(message)s'
datefmt  =

执行时,出现以下错误KeyError

  

回溯(最近通话最近):文件   “ C:/用户/M/PycharmProjects/LOGGING/Log_data_config_file.py”,第6行,   在       logging.config.fileConfig('Log_parameters.ini')文件“ C:\ Users \ M \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ logging \ config.py”,   第79行,在fileConfig中       处理程序= _install_handlers(cp,formatters)文件“ C:\ Users \ M \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ logging \ config.py”,   _install_handlers中的第134行       section = cp [“ handler_%s”%hand]文件“ C:\ Users \ M \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ configparser.py”,   第958行,在 getitem       引发KeyError(key)KeyError:'handler_handle1'

3 个答案:

答案 0 :(得分:0)

您需要修复配置文件中的几件事:

1)将root添加到loggers部分:

[loggers]
keys = root,sakthi

2)添加logger_root部分:

[logger_root]
level=NOTSET
handlers=handle1

3)将[logger_handle1]部分重命名为handler_handle1

之后,您将拥有以下配置文件:

[loggers]
keys = root,sakthi
[handlers]
keys = handle1
[formatters]
keys = simpleformatter

[logger_root]
level=NOTSET
handlers=handle1

[logger_sakthi]
level = DEBUG
handlers = handle1
qualname = compiler.parser
propogate = 0

[handler_handle1]
class = FileHandler
level = DEBUG
formatter = simpleformatter
args= ('Configg_log','w')

[formatter_simpleformatter]
format=F1 %(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt  =

代码将正确运行,并将此输出写入Configg_log文件:

F1 2019-04-22 00:29:37,091 - sakthi - DEBUG - 0 iteration, item=1
F1 2019-04-22 00:29:37,091 - sakthi - DEBUG - 1 iteration, item=2
F1 2019-04-22 00:29:37,091 - sakthi - DEBUG - 2 iteration, item=3

答案 1 :(得分:0)

我认为, [logger_handle1]应该是[handler_handle1]

答案 2 :(得分:0)

handle1 不是记录器而是处理程序,因此键已被识别为 - [处理程序] 键 = 句柄 1

它会用单数搜索-- 所以它应该是 handler_handle1 同意@SkyOcean

另一种方式——

如果你想自己添加一个新的记录器然后添加 [记录者] 键 = sakthi,handle1 然后 logger_handle1 将起作用