Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current log level in python logging module

I'm trying to create a basic logger that will be colored without external packages,

# these have to be the first functions so I can use it in the logger settings def create_log_name(log_path="{}/log", filename="zeus-log-{}.log"):     if not os.path.exists(log_path.format(os.getcwd())):         os.mkdir(log_path.format(os.getcwd()))     find_file_amount = len(os.listdir(log_path.format(os.getcwd())))     full_log_path = "{}/{}".format(log_path.format(os.getcwd()), filename.format(find_file_amount + 1))     return full_log_path   def set_color_value(levelname):     log_set = {         "INFO": "\033[92m{}\033[0m",         "WARNING": "\033[93m{}\033[0m",         "DEBUG": "\033[94m{}\033[0m",         "ERROR": "\033[91m{}\033[0m",         "CRITICAL": "\033[91m{}\033[0m"     }     return log_set[levelname].format(levelname)  logger = logging.getLogger("zeus-log") logger.setLevel(logging.DEBUG) file_handler = logging.FileHandler(     filename=create_log_name(), mode="a+" ) file_handler.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) file_format = logging.Formatter(     '%(asctime)s;%(name)s;%(levelname)s;%(message)s' ) console_format = logging.Formatter(     "[%(asctime)s {}] %(message)s".format(set_color_value()), "%H:%M:%S" ) file_handler.setFormatter(file_format) console_handler.setFormatter(console_format) logger.addHandler(console_handler) logger.addHandler(file_handler) 

So as of right now, all I need to do is get the current log level that will be set in the logging.Formatter and send it to my little function:

console_format = logging.Formatter(     "[%(asctime)s {}] %(message)s".format(set_color_value()), "%H:%M:%S" ) 

Is it possible to get the current log level from the logging package?


For example, lets say I pass logger.INFO("test") I need a way to get that INFO part in as a string, from there, set_color_value("INFO") should return:

enter image description here

like image 794
wahwahwah Avatar asked Aug 28 '17 16:08

wahwahwah


2 Answers

If you're using the root logger, for example because you called logging.basicConfig() then you can use

import logging logging.root.level 

For example

if logging.DEBUG >= logging.root.level:     # Do something 
like image 99
bcattle Avatar answered Sep 28 '22 04:09

bcattle


Yes, you can check the logger level by

level = logger.level 
like image 26
Milán Vásárhelyi Avatar answered Sep 28 '22 04:09

Milán Vásárhelyi