Using a variable while calling logger.setLevel

2020-05-29 12:36发布

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')
Log.setLevel(logging.DEBUG)

But I'd like to have this:

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

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.

5条回答
霸刀☆藐视天下
2楼-- · 2020-05-29 13:13

I find that leveraging an optional environmental variable is very convenient and flexible:

class Foo():
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        level = logging.getLevelName(os.environ.get('LOG_LEVEL', 'ERROR'))
        logging.basicConfig(level=level)

    def bar(self):
        self.logger.debug('Log something')
查看更多
3楼-- · 2020-05-29 13:16

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.

查看更多
Evening l夕情丶
4楼-- · 2020-05-29 13:32

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")
查看更多
疯言疯语
5楼-- · 2020-05-29 13:38

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())
查看更多
【Aperson】
6楼-- · 2020-05-29 13:39

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()
查看更多
登录 后发表回答