簡體   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