繁体   English   中英

如何从配置文件设置登录 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 的变量。

The second one, that I also suggest, would be to set handlers with python logging class https://docs.python.org/3/library/logging.config.html

您始终可以使用 Python 内置配置文件解析器

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

    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$ 

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

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

20 30 10 40

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM