Expanding on a comment by bar for better visibility.
Python 3.11 added an utility function that helps with this issue:
logging.getLevelNamesMapping.
From the docs:
Returns a mapping from level names to their corresponding logging levels. For example, the string “CRITICAL” maps to logging.CRITICAL.
We can solve the original question (How do I convert a level string to a numerical level) using this mapping:
import logging
mapping = logging.getLevelNamesMapping()
result = mapping["INFO"]
Note that the log level names only appear as uppercase in the mapping:
{'CRITICAL': 50,
'FATAL': 50,
'ERROR': 40,
'WARN': 30,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0}
If you need to support lowercase too, just call .upper() first:
def get_log_level_value(log_level_name: str) -> int:
mapping = logging.getLevelNamesMapping()
return mapping[log_level_name.upper()]
> get_log_level_value("info")
20
> get_log_level_value("INFO")
20
You may want to cache the mapping returned by getLevelNamesMapping if you need to reference it a lot, given that it copies a new dict on every call. From the docs:
The returned mapping is copied from an internal mapping on each call to this function.