Using a variable while calling logger.setLevel

Solution 1:

You should also be able to do this:

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

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.

Solution 2:

I had problems with python 3 and got this working for me: https://docs.python.org/3/howto/logging.html

# myapp.py
import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()

Solution 3:

logging.setLevel() takes an int or a str.

So the following works just fine (at least in Python 3.7):

logger = logging.getLogger(__name__)
logger.setLevel("DEBUG")

Solution 4:

What about using getattr on logging module?

import logging
str_level = 'DEBUG'
level = getattr(logging, str_level)
logger = logging.getLogger("my_logger")
logger.setLevel(level)
print(logger.getEffectiveLevel())