2

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

the_frank
  • 105
  • 3
  • 12

2 Answers2

3

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()
)
YosSaL
  • 667
  • 6
  • 15
-7

I concatenated the string in a another variable then ran an exec on the variable.

my_script_config:

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

script:

import my_script_conf as msc
SET_LEVEL = 'logger.setLevel(' + msc.LOG_LEVEL + ')
BASIC_LEVEL = 'logging.basicConfig(level=' + msc.LOG_LEVEL + ')'

logger = logging.getLogger(__name__)
exec(SET_LEVEL)
exec(BASIC_LEVEL)
the_frank
  • 105
  • 3
  • 12
  • 4
    exec is a horrible idea. Better would be to simply import logging in your config script, and use ```LOG_LEVEL =logging.DEBUG```. Or, if you really must use a string, you could later use ```getattr(logging, msc.LOG_LEVEL)``` . Pretty much whenever you find yourself using eval, you should realize you are doing something wrong. eval can be dangerous – JonB Apr 12 '17 at 14:24
  • This was moved out and placed on the cli using the click cli module. Inspired by http://stackoverflow.com/questions/14097061/easier-way-to-enable-verbose-logging – the_frank Apr 13 '17 at 16:02