如何从配置文件设置登录 python 的级别

How to set level for logging in python from configuration file

我正在尝试为我的 python 代码设置记录器,我想从配置文件中设置日志级别。但是我做不到。下面给出代码,如果你注意到下面给出的代码可以看到logger.setLevel(logging.INFO)。我不想直接提及硬编码值 logging.INFO。需要从配置文件中获取这个,可以吗?

    import logging
    from logging.config import fileConfig
    from datetime import date


    class Log:
        @staticmethod
        def trace():
            today = date.today()

            # dd/mm/YY
            d1 = today.strftime("%d_%m_%Y")

            # Gets or creates a logger
            logger = logging.getLogger(__name__)

            # set log level
            logger.setLevel(logging.INFO)

            # define file handler and set formatter
            file_handler = logging.FileHandler('log/'+d1+'_logfile.log')
            formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s')
            file_handler.setFormatter(formatter)

            # add file handler to logger
            logger.addHandler(file_handler)

            console_handler = logging.StreamHandler()
            console_handler.setFormatter(formatter)
            logger.addHandler(console_handler)
            return logger

如果我没理解错的话,您需要一种在运行时设置日志记录级别的方法,而不是硬编码值。我会说你有两个选择。

第一个解决方案是解析您的配置文件,并相应地设置日志记录级别。如果您不想在每次调用 Log class 时都解析它,您可以在 main 中设置一个传递给 Log class.[= 的变量13=]

第二个,我也建议,将设置处理程序 python 日志记录 class https://docs.python.org/3/library/logging.config.html

日志记录级别 (logging.INFO) 是一个整数值。你能从你的配置文件中传递数字来设置日志级别吗

print(logging.INFO)
print(logging.WARN)
print(logging.DEBUG)
print(logging.ERROR)

20 30 10 40

您可以随时使用 Python 内置 Configuration file parser

在配置文件中获取日志级别并读取该值。由于该值将在字符串中,您可以在代码中定义字典映射。请参阅下面的示例。

    import configparser
    config= configparser.ConfigParser()
    config.read('configfile')
    log_level_info = {'logging.DEBUG': logging.DEBUG, 
                        'logging.INFO': logging.INFO,
                        'logging.WARNING': logging.WARNING,
                        'logging.ERROR': logging.ERROR,
                        }
    print(config['DEFAULT']['LOG_LEVEL'])
    my_log_level_from_config = config['DEFAULT']['LOG_LEVEL']
    my_log_level = log_level_info.get(my_log_level_from_config, logging.ERROR)
    logger.setLevel(my_log_level)

您的配置文件如下所示:

user@Inspiron:~/code/advanced_python$ cat configfile 
[DEFAULT]
LOG_LEVEL = logging.INFO 

user@Inspiron:~/code/advanced_python$