python日志记录模块的日志记录问题 [英] Logging issues with python logging module

查看:112
本文介绍了python日志记录模块的日志记录问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python日志记录模块.我正在初始化具有以下数据的文件

I am using python logging module. I am initialising file having following data

def initialize_logger(output_dir):
    '''
    This initialise the logger
    :param output_dir:
    :return:
    '''
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    format = '%(asctime)s - %(levelname)-8s - %(message)s'
    date_format = '%Y-%m-%d %H:%M:%S'
    if 'colorlog' in sys.modules and os.isatty(2):
        cformat = '%(log_color)s' + format
        f = colorlog.ColoredFormatter(cformat, date_format,
                                      log_colors={'DEBUG': 'green', 'INFO': 'green',
                                                  'WARNING': 'bold_yellow', 'ERROR': 'bold_red',
                                                  'CRITICAL': 'bold_red'})
    else:
        f = logging.Formatter(format, date_format)
    #ch = logging.FileHandler(output_dir, "w")
    ch = logging.StreamHandler()
    ch.setFormatter(f)
    root.addHandler(ch)

由于只有一个streamHandler,但是我在控制台上得到的两张照片是

As there is only one streamHandler, But I am getting two prints on my console as

INFO:root:clearmessage:%ss1=00

2017-12-21 17:07:20 - INFO     - clearmessage:%ss1=00

INFO:root:clearmessage:%ss2=00

2017-12-21 17:07:20 - INFO     - clearmessage:%ss2=00

每条消息均打印为RootInfo.知道为什么我要打印两张照片.在上面的代码中,您可以忽略颜色代码.

Every message is printed as Root and Info. Any idea Why I am getting two prints. In the above code you can ignore color code.

推荐答案

您有两个处理程序.在添加新的处理程序之前,请先清除这些处理程序:

You have two handlers. Clear the handlers before you add a new one:

root.handlers = [] # clears the list
root.addHandler(ch) # adds a new handler

这篇关于python日志记录模块的日志记录问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆