log messages appearing twice with Python Logging

后端 未结 8 1385
天命终不由人
天命终不由人 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:05

    It seems that if you output something to the logger (accidentally) then configure it, it is too late. For example, in my code I had

    logging.warning("look out)"
    
    ...
    ch = logging.StreamHandler(sys.stdout)
    root = logging.getLogger()
    root.addHandler(ch)
    
    root.info("hello")
    

    I would get something like (ignoring the format options)

    look out
    hello
    hello
    

    and everything was written to stdout twice. I believe this is because the first call to logging.warning creates a new handler automatically, and then I explicitly added another handler. The problem went away when I removed the accidental first logging.warning call.

提交回复
热议问题