Getting the logging level from text representation
__peter__ at web.de
Wed Sep 2 11:50:38 CEST 2015
Antoon Pardon wrote:
> I am writing an application that will do the necessary logging.
> However I want the level of logging to be deciced by a value
> in a config file. Like the following:
> loglevel = WARNING
> But I can't find a function that does this.
> The reverse is possible with logging.getLevelName. The documentation
> also states this:
> Changed in version 3.4: 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.
> So what is the supposed correct way to handle this? Preferably one
> that works when additional levels have been introduced.
Why do you want to convert the name into a number? You can use it directly:
>>> import logging
>>> root = logging.getLogger()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/logging/__init__.py", line 1236, in setLevel
self.level = _checkLevel(level)
File "/usr/lib/python3.4/logging/__init__.py", line 179, in _checkLevel
raise ValueError("Unknown level: %r" % level)
ValueError: Unknown level: 'ROCKET'
>>> logging.addLevelName(10987654321, "ROCKET")
More information about the Python-list