Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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$ 

Solution 2:

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

Solution 3:

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

Post a Comment for "How To Set Level For Logging In Python From Configuration File"