Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 logging module: set variable for logging levels in config

I am using the logging module in Python 3.5, I feel like I have done this before, but I would like like to change the logging level with a constant supplied by my config file.

Currently I am using:

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
logger.setLevel(logging.INFO)

I would like to declare INFO, DEBUG etc in the config file and replace using the literal.

my_script_config:

LOG_LEVEL = 'DEBUG' #this value to be modified by user.

script:

import my_script_conf as msc
SET_LEVEL = 'logging.' + msc.LOG_LEVEL
BASIC_LEVEL = 'level=' + SET_LEVEL

logger = logging.getLogger(__name__)
logging.basicConfig(BASIC_LEVEL)
logger.setLevel(SET_LEVEL)

Python gets upset by this, any help on my terrible coding would be much appreciated. Any route to achieve the same result, I basically want it readable and easy to use, to have the logging modules level set in the external config file seems like the most sensible option. You pythonista's may have other ideas!

Thanks, Frank

like image 524
the_frank Avatar asked Apr 16 '26 19:04

the_frank


1 Answers

Not sure to fully understood your question, but in case somebody wants to set python log level using env variables or config files, you can simply use strings and it will be handled:

import logging
logging.basicConfig(
    level=os.environ.get('LOGLEVEL', 'INFO').upper()
)
like image 60
YosSaL Avatar answered Apr 19 '26 11:04

YosSaL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!