Previous answers discuss the matter sufficiently, but for general viewing I would like to add an alternative way to translate logging level strings to the internal integer values.
getattr(logging, level_string)
Why? Just because the logging.getLevelName()
function has a nasty feature to return you those "Level X" strings for invalid arguments.
Let's imagine that you are writing a Flask application that allows setting logging level in the instance configuration file (for example; LOGGING_LEVEL = "WARNING"
). That qualifies as user input in my books and in my opinion you should be able to deal with invalid values. The third argument, fallback value, allows us to do this:
app = Flask(...)
app.config.from_pyfile('application.conf')
app.logger.setLevel(
getattr(
logging,
str(app.config.get('LOG_LEVEL', 'DEBUG')),
logging.DEBUG
)
)
Now your code should be able to tolerate erroneous/missing configuration value and default to DEBUG logging mode in such cases.
All this is unnecessary and of no concern to you, if your logging level value is not user input (and thus unlikely to be missing or nonsensical). Then you're fine with logging.getLevelName()
, I think.
My 5 cents is that people writing the logging module missed an obvious opportunity to address all this by providing us with optional third function argument (the fallback value), but it is what it is...
Hope this helps someone.