How to convert python protocol level name to integer code

Starting with Python 3.2, logging.Logger.setLevel takes a line level, such as "INFO," instead of the corresponding integer constant. This is very convenient, except that you cannot compare levels in this way, and most other logging methods accept only integers. How to convert a level string to a numeric level using the functions provided by the logging package? In particular, I would like something that does this:

 >>> logging.???('INFO') == logging.INFO True 
+5
source share
3 answers

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 >>> 
+7
source

.level returns the numerical level of the registration event.

Demo:

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

The logging module has several attributes that allow you to use this function. They are prefixed with an underline that implies confidentiality, so using them is not a good idea. But:

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 completes the _checkLevel dictionary, which contains all registered levels (and addLevelName updated).

There is an additional element called _levelToName that contains the inverse mapping. This is publicly available using the getLevelName method.

+2
source

Source: https://habr.com/ru/post/1244033/


All Articles