简体   繁体   中英

How to set level for logging in python from configuration file

I am trying to set loggers for my python code, I want to set the level of the log from the configuration file. But unable to do by me. Here the code is given below, If you noticed that in the given below code can see logger.setLevel(logging.INFO) . I don't want to directly mention as a hardcoded value logging.INFO . Need to get this from the config file, is it possible?

    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

If I understood correctly, you need a way to set your logging level at runtime instead of a hard-coded value. I would say you have two options.

The first solution would be to parse your configuration file, and set the level of logging accordingly. If you don't want to parse it everytime the Log class is invoked, in your main you can set a variable that you pass to the 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

You can always use Python built-in Configuration file parser

Have the log levels in a config file and read that value. Since that value will be in string, you can define the dictionary mapping in your code. See below for an example.

    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)

Your config file would be like below:

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

user@Inspiron:~/code/advanced_python$ 

logging level (logging.INFO) is an integer value. can you pass numbers from your config file to set log level

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

20 30 10 40

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.

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