Replace default handler of Python logger

前端 未结 2 1925
刺人心
刺人心 2021-01-31 02:20

I\'ve got the following code running on each request of a wsgi (web2py) application:

import logging, logging.handlers
from logging import StreamHandler, Formatte         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 03:08

    Perhaps the following example will help. Basically you can either remove the handlers of the logger you'd like to disable, or don't propagate with the logger you are logging from.

    $ cat testlog.py
    import logging
    logging.basicConfig(filename='foo', level=logging.DEBUG)
    root_logger = logging.getLogger()
    root_logger.debug('bar')
    
    my_logger = logging.getLogger('my_logger')
    FORMAT = "%(process)s %(thread)s: %(message)s"
    formatter = logging.Formatter(fmt=FORMAT)
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    
    my_logger.addHandler(handler)
    my_logger.setLevel(logging.DEBUG)
    my_logger.info('baz')
    
    my_logger.propagate = False
    my_logger.info('foobar')
    
    my_logger.propagate = True
    my_logger.info('foobaz')
    root_logger.handlers = []
    my_logger.info('barbaz')
    
    $ python testlog.py
    5927 140735224465760: baz
    5927 140735224465760: foobar
    5927 140735224465760: foobaz
    5927 140735224465760: barbaz
    
    $ cat foo
    DEBUG:root:bar
    INFO:my_logger:baz
    INFO:my_logger:foobaz
    

提交回复
热议问题