python 3.6
How do you set the logging level
I would like to run instantiate a logging class with the following code
import logging
from sys import stdout
from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL, StreamHandler
logger = logging.getLogger(__name__)
logging_level = "DEBUG"
valid_logging_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
if logging_level not in valid_logging_levels:
raise ValueError(f"Logging level must be one of the following: {valid_logging_levels}")
Currently I'm using this syntax to set the logging level, but it's really long
sys_out = StreamHandler(stdout)
if not [isinstance(handler, StreamHandler) for handler in logger.handlers]:
logger.addHandler(sys_out)
if logging_level == "DEBUG":
logger.setLevel(DEBUG)
elif logging_level == "INFO":
logger.setLevel(INFO)
elif logging_level == "WARNING":
logger.setLevel(WARNING)
elif logging_level == "ERROR":
logger.setLevel(ERROR)
elif logging_level == "CRITICAL":
logger.setLevel(CRITICAL)
However, that's really long. I thought I could shorten it like the following
log_level = logger.getLevelName(logging_level)
logger.setLevel(log_level)
However, when I run it I get the error message 'Logger' object has no attribute 'getLevelName'
Is there a better way to set a custom logging level?
Thanks in advance!
log_levels = {
'DEBUG': DEBUG,
'INFO' : INFO,
'WARNING':WARNING,
'ERROR': ERROR,
'CRITICAL':CRITICAL
}
and then you can do like this
logger.setLevel(log_levels.get(logging_level))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.