Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting logging levels using a variable

I haven't quite got the hang of Python enough to figure this out on my own, so I'm asking for help.

I have various logging messages scattered throughout my python module. I would like the code calling the module to be able to set the debug level by doing:

module.DEBUG = INFO

for instance. But I'm not able to translate that into work. I've got global variable "DEBUG", and I would like it to be interpreted in the following line, rather than DEBUG acting as a literal string, which is what I think is happening:

 logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)

How can I make that string be treated as a variable instead of a literal (if that's what is happening?)

Thanks!

--Matt

like image 328
Matt Simmons Avatar asked Sep 02 '14 19:09

Matt Simmons


1 Answers

If you would like the calling code control the logging level on your module, you should consider accepting the log level as a parameter in your module. Below is some sample code on how you can do that:

import logging

class MyModule(object):
"""
Sample module to demonstrate setting of loglevel on init
"""

    def __init__(self, logLevel):
        #logLevel, a string, should be one of the levels of the logging modules. Example: DEBUG, INFO, WARNING etc.

        #Translate the logLevel input string to one of the accepted values of the logging module. Change it to upper to allow calling module to use lowercase 
        #If it doesn't translate default to something like DEBUG which is 10
        numeric_level = getattr(logging, logLevel.upper(), 10)

        logging.basicConfig(filename='example.log', level=numeric_level)


    def testLogger(self):
        #logging object that you defined the level in init is used here for some sample logging
        logging.debug('see this at debug level')
        logging.info('see this at info and debug')
        logging.warning('see this at warn, info and debug')


if __name__ == "__main__":
    MM= MyModule('info')
    MM.testLogger()
like image 176
user3885927 Avatar answered Nov 11 '22 05:11

user3885927