Logging issues with python logging module

2019-08-13 20:03发布

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)

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

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.

1条回答
做个烂人
2楼-- · 2019-08-13 21:00

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
查看更多
登录 后发表回答