Python Logging - Disable logging from imported modules

前端 未结 10 821
清酒与你
清酒与你 2020-12-12 12:52

I\'m using the Python logging module, and would like to disable log messages printed by the third party modules that I import. For example, I\'m using something like the fo

10条回答
  •  天命终不由人
    2020-12-12 13:19

    If you're going to use the python logging package, it's a common convention to define a logger in every module that uses it.

    logger = logging.getLogger(__name__)
    

    Many popular python packages do this, including requests. If a package uses this convention, it's easy to enable/disable logging for it, because the logger name will be the same name as the package (or will be a child of that logger). You can even log it to the same file as your other loggers.

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    
    requests_logger = logging.getLogger('requests')
    requests_logger.setLevel(logging.DEBUG)
    
    handler = logging.StreamHandler()
    handler.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    requests_logger.addHandler(handler)
    

提交回复
热议问题