41

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

4 Answers 4

48

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
>>> 
Sign up to request clarification or add additional context in comments.

3 Comments

This is exactly what I was looking for. A query without modifying the state of any logger.
@ronkov's solution seems to be more robust
Upvoted as this solution is more backwards compatible.
21

You can also use:

import logging
logging.getLevelName('INFO')

As noted in the comments, in newer python versions you should use:

import logging
logging.getLevelNamesMapping()['INFO']

5 Comments

Past 3.4.2, this is by far the simplest way to do it
I absolutely can't recommend to use logging.getLevelName(). The function has a messed up interface, and you're never sure whether a str or an int is returned. Even with str, you can't tell whether the string represents a real level (like "INFO") or an invalid value (like "level info"). No value checking, no type checking -> don't use it.
Python 3.11 introduced getLevelNamesMapping docs.python.org/3/library/… which is a mapping from string to a level name in Logging Levels docs.python.org/3/library/logging.html#logging-levels (int). This should clarify semantics.
I'm sorry for the down vote, but for people who come here, this function's behavior changed about Python 3.4. Use getLevelNamesMapping() instead.
Thanks @chrisinmtown I just added that to the answer
8

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.

Comments

2

Expanding on a comment by bar for better visibility.

Python 3.11 added an utility function that helps with this issue: logging.getLevelNamesMapping.

From the docs:

Returns a mapping from level names to their corresponding logging levels. For example, the string “CRITICAL” maps to logging.CRITICAL.

We can solve the original question (How do I convert a level string to a numerical level) using this mapping:

import logging
mapping = logging.getLevelNamesMapping()
result = mapping["INFO"]

Note that the log level names only appear as uppercase in the mapping:

{'CRITICAL': 50,
 'FATAL': 50,
 'ERROR': 40,
 'WARN': 30,
 'WARNING': 30,
 'INFO': 20,
 'DEBUG': 10,
 'NOTSET': 0}

If you need to support lowercase too, just call .upper() first:

def get_log_level_value(log_level_name: str) -> int:
    mapping = logging.getLevelNamesMapping()
    return mapping[log_level_name.upper()]


> get_log_level_value("info")
20

> get_log_level_value("INFO")
20

You may want to cache the mapping returned by getLevelNamesMapping if you need to reference it a lot, given that it copies a new dict on every call. From the docs:

The returned mapping is copied from an internal mapping on each call to this function.

1 Comment

Kinda wordy :) I upvoted anyhow thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.