log messages appearing twice with Python Logging

后端 未结 8 1384
天命终不由人
天命终不由人 2020-12-04 18:39

I\'m using Python logging, and for some reason, all of my messages are appearing twice.

I have a module to configure logging:

# BUG: It\'s outputting         


        
8条回答
  •  再見小時候
    2020-12-04 19:08

    I was getting a strange situation where console logs were doubled but my file logs were not. After a ton of digging I figured it out.

    Please be aware that third party packages can register loggers. This is something to watch out for (and in some cases can't be prevented). In many cases third party code checks to see if there are any existing root logger handlers; and if there isn't--they register a new console handler.

    My solution to this was to register my console logger at the root level:

    rootLogger = logging.getLogger()  # note no text passed in--that's how we grab the root logger
    if not rootLogger.handlers:
            ch = logging.StreamHandler()
            ch.setLevel(logging.INFO)
            ch.setFormatter(logging.Formatter('%(process)s|%(levelname)s] %(message)s'))
            rootLogger.addHandler(ch)
    

提交回复
热议问题