Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the log level of an imported module

Tags:

python

logging

Suppose your code is using a module that uses log statements with logging.info from the module as opposed to logger.info from a logger instance, and that you don't have control to modify the module that is in use.

Is it possible to customize the logging levels for JUST the imported module without requesting a code change from the maintainers?

These questions have described a very straightforward approach for changing the logging level for a particular module.
How do I disable log messages from the Requests library?
Python Logging - Disable logging from imported modules

The code below implements that solution as described to log only ERROR messages from that module, but it did not turn of WARNING messages as expected.

The test module produces the same output when referring to the noisy_noise module as a string literal and by using the name of the imported symbol.

What is missing from run_me.py to suppress WARN messages?

noisy_noise.py

EDIT: Assume this module represents one that is imported from other maintainers and is closed for modification

import logging

def log_things():
    logging.warn('WARNING')
    logging.info('INFORMATION')
    logging.error('DANGER')

run_me.py

import logging
import noisy_noise
import sys

def main(args):
    logging.getLogger(noisy_noise.__name__).setLevel(logging.ERROR)
#    logging.getLogger('noisy_noise').setLevel(logging.ERROR)

    noisy_noise.log_things()

if __name__ == '__main__':
   sys.exit(main(sys.argv[1:]))
$ python run_me.py
WARNING:root:WARNING
ERROR:root:DANGER
like image 456
Val H Avatar asked Jun 26 '19 15:06

Val H


1 Answers

Yes it is possible if you know the name of the logger.

Example: change the log level of urllib3 to WARNING

logging.getLogger("urllib3").setLevel(logging.WARNING)
like image 101
balderman Avatar answered Sep 21 '22 02:09

balderman