How to convert python logging level name to integer code

Question:

As of Python 3.2, logging.Logger.setLevel accepts a string level such as ‘INFO’ instead of the corresponding integer constant. This is very handy except that you can’t compare the levels numerically that way and most other logging methods accept integers only. How do I convert a level string to a numerical level using the functions provided by the logging package? Specifically, I would like something that does this:

>>> logging.???('INFO') == logging.INFO
True
Asked By: Mad Physicist

||

Answers:

.level returns the numeric level of the logging event.

Demo:

>>> logger = logging.getLogger()
>>> logger.setLevel('INFO')
>>> logger.level == logging.INFO
True

To avoid the concerns that OP raised in his comment you could use a temporary logger like this:

import logging
import uuid

logging.basicConfig()
logger = logging.getLogger(__file__)


def logLevelToInt(level):
    '''convert given level to int'''
    _id = str(uuid.uuid4())
    logger = logging.getLogger(_id)
    logger.setLevel(level)
    rval = logger.level
    logging.Logger.manager.loggerDict.pop(_id)
    return rval

example:

>>> from basic_args import logLevelToInt
>>> logLevelToInt('DEBUG')
10
>>> logLevelToInt('CRITICAL')
50
>>> import logging
>>> logLevelToInt(logging.INFO)
20
>>>
Answered By: styvane

How about using something like

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> getattr(logging, 'INFO')
20
>>> getattr(logging, 'DEBUG')
10
>>> getattr(logging, 'ERROR')
40
>>> 
Answered By: Vinay Sajip

There are a couple of attributes in the logging module that allow this functionality. They are prefixed with an underscore, implying privacy, so using them is not a good idea. However:

At the highest level, there is _checkLevel, which takes a level that is either a string or an integer and either returns the corresponding existing level or raises a ValueError.

_checkLevel wraps the dictionary _nameToLevel, which contains all the registered levels (and gets updated by addLevelName).

There is an additional member called _levelToName, which contains the reverse mapping. It is publicly accessible via the getLevelName method.

Answered By: Mad Physicist

You can also use:

import logging
logging.getLevelName('INFO')
Answered By: ronkov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.