Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable while calling logger.setLevel

Tags:

python

logging

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.

like image 228
Jak Avatar asked Apr 26 '12 11:04

Jak


People also ask

What is logger Setlevel in Python?

The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on." Check under Handlers: http://docs.python.org/2.7/howto/logging.html#logging-advanced-tutorial.

What is logging getLogger (__ Name __)?

logger = logging.getLogger(__name__) This means that logger names track the package/module hierarchy, and it's intuitively obvious where events are logged just from the logger name. Sounds like good advice.

What is propagate in logger in Python?

Python Logger Propagate: Decides whether a log should be propagated to the logger's parent. By default, its value is True. A level: Like the log handler level, the logger level is used to filter out “less important” logs.


2 Answers

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.

like image 76
Sébastien RoccaSerra Avatar answered Oct 09 '22 18:10

Sébastien RoccaSerra


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() 
like image 38
svenhornberg Avatar answered Oct 09 '22 17:10

svenhornberg