Python Logging - Disable logging from imported modules

前端 未结 10 833
清酒与你
清酒与你 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:17

    I had the same problem. I have a logging_config.py file which I import in all other py files. In logging_config.py file I set root logger logging level to ERROR (by default its warning):

    logging.basicConfig(
        handlers=[
            RotatingFileHandler('logs.log',maxBytes=1000, backupCount=2),
            logging.StreamHandler(), #print to console
        ],
        level=logging.ERROR
    )
    

    In other modules I import logging_config.py and declare a new logger and set its level to debug:

    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG)
    

    This way everything I log in my py files is logged, but stuff logged at debug and info level by imported modules like urllib, request,boto3 etc is not logged. If there is some error in those import module then its logged, since I set root loggers level to ERROR.

提交回复
热议问题