Using a variable while calling logger.setLevel
Asked Answered
S

6

70

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.

Shutout answered 26/4, 2012 at 11:45 Comment(2)
You should use uppercase in your dict values: ERROR: logging.ERROR etcPerilous
Also, Have a look at the logging documentation on this: docs.python.org/howto/logging.html#logging-levels. Logging levels are just numeric values.Upchurch
R
155

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.

Roshelle answered 12/3, 2013 at 17:31 Comment(1)
quote: "In Python versions earlier than 3.4, this function could also be passed a text level, and would return the corresponding numeric value of the level. This undocumented behaviour was considered a mistake, and was removed in Python 3.4, but reinstated in 3.4.2 due to retain backward compatibility."Catalpa
S
13

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")
Stamper answered 26/3, 2019 at 9:37 Comment(1)
According to the documentation this works since Python 3.2: Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as INFO. Note, however, that levels are internally stored as integers, and methods such as e.g. getEffectiveLevel() and isEnabledFor() will return/expect to be passed integers. Source: docs.python.org/3/library/logging.html#logging.Logger.setLevelCharmian
C
8

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()
Chowchow answered 20/8, 2015 at 9:34 Comment(1)
+1 I like the way you have all the logging calls within a function definition. This reduces the likelyhood of import lock problems with logging.Luminescence
R
7

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())
Religieux answered 31/10, 2017 at 4:23 Comment(0)
O
4

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')
Outgoings answered 9/10, 2019 at 18:29 Comment(0)
L
0

I was able to get this working below. I added a environment variable section as I am using this in a Docker but you can add it in as you see fit. This way you can select what you need and re-run your script.

#Manual Testing Variables If Needed
#os.environ["LOG_LEVEL_SELECTOR"] = "DEBUG, INFO, or ERROR"

#Setting Log Level Test
logger = logging.getLogger('json')
logger.addHandler(json_handler_out)
logger_levels = {
    'ERROR' : logging.ERROR,
    'INFO' : logging.INFO,
    'DEBUG' : logging.DEBUG
}
logger_level_selector = os.environ["LOG_LEVEL_SELECTOR"]
logger.setLevel(logger_level_selector)
Libation answered 23/9, 2020 at 19:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.