2014-09-02 111 views
2

我还没有完全掌握足够的Python来解决这个问题,所以我在寻求帮助。使用变量设置日志记录级别

我有各种日志消息分散在我的python模块中。我想在代码中调用该模块能够通过这样设置调试级别:

module.DEBUG = INFO

例如。但我无法将其转化为工作。我有全局变量“调试”,我想它在下面的行进行解释,而不是DEBUG充当文本字符串,这是我认为正在发生的事情:

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

我怎样才能使该字符串被视为一个变量而不是文字(如果这就是发生了什么?)

谢谢!

--Matt

+0

调试是一个级别。我想你的意思是说你想设置日志级别 – Elisha 2014-09-02 19:39:49

+0

logging.DEBUG不是字面的。它是一个整数。 ('logging.DEBUG == 10') – Elisha 2014-09-02 19:41:56

回答

4

如果你想调用代码控制模块上的日志记录级别,你应该考虑接受日志级别为你的模块中的一个参数。下面是你如何做到这一点的一些示例代码:

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