Python – Using a variable while calling logger.setLevel


Does anyone know if there is a way to use a variable in the setlevel() function of Python's Logging module?

At the moment I am using this:

Log = logging.getLogger('myLogger')

But I'd like to have this:

Log = logging.getLogger('myLogger')
levels = {'CRITICAL' : logging.critical,
    'ERROR' : logging.error,
    'WARNING' : logging.warning,
    'INFO' :,
    'DEBUG' : logging.debug
level = levels['INFO']

But it doesn't seem to work – it just doesn't log anything.

I'm doing this so that I can set the logging level for a whole bunch of scripts from a variable in a single config file.

Best Solution

You should also be able to do this:

Log = logging.getLogger('myLogger')
level = logging.getLevelName('INFO')

The logging.getLevelName(lvl) function works both ways. I use it, it works (you should check your python implementation though).

This saves you the trouble to maintain your own dictionary, and reduces the possibility of typo errors.