pythonpython-3.xpython-logging

How to convert python logging level name to integer code


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

Solution

  • 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']