1

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.

2
  • 1
    May be you call initialize_logger() twice Commented Dec 21, 2017 at 11:48
  • But I saw both messages are printed with diff message format. I am calling another statement like addHandler(logging.NullHandler()). Will it causing issue Commented Dec 21, 2017 at 11:49

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it worked. Somewhere in the code i may be calling it twice. It worked However. Do you know anything for html logger in python
I think the getLogger() call will create a handler implicitly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.