Python logging – determine level number from name

Question:

Python logging levels can be registered using logging.addLevelName. Is there a method to obtain the Python logging number from a level name?

Asked By: Casebash

||

Answers:

After you call addLevelName, the resulting level is treated exactly the same as all of the standard ones:

>>> import logging
>>> logging.getLevelName(10)
'DEBUG'
>>> logging.getLevelName('DEBUG')
10
>>> logging.addLevelName(15, 'DEBUGGISH')
>>> logging.getLevelName(15)
'DEBUGGISH'
>>> logging.getLevelName('DEBUGGISH')
15

The fact that getLevelName can map names to numbers as well as numbers to names is not actually documented in Python 2.x, nor does the name give any hint that it should… but a quick look at the source shows why it works.

Answered By: abarnert

If you can deal with a default level, checking the type of the result is a decent workaround.

int_level = logging.getLevelName(string_level)
  if type(int_level) != int:
    int_level = 20 # default to INFO
Answered By: apardoe
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.