使用变量设置日志记录级别

时间:2014-09-02 19:35:42

标签: python logging xdebug

我还没有完全掌握Python以便自己解决这个问题,所以我正在寻求帮助。

我的python模块中散布着各种日志消息。我希望调用模块的代码能够通过执行以下操作来设置调试级别:

module.DEBUG = INFO

例如

。但我无法将其转化为工作。我有全局变量“DEBUG”,我希望它在下面的行中解释,而不是DEBUG作为文字字符串,这是我认为正在发生的事情:

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

如何将该字符串视为变量而不是文字(如果发生了什么?)

谢谢!

- 亚光

1 个答案:

答案 0 :(得分:5)

如果您希望调用代码控制模块上的日志记录级别,则应考虑接受日志级别作为模块中的参数。以下是一些示例代码,说明如何执行此操作:

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()