使用变量设置日志级别
我还没有完全掌握Python,所以自己搞不定这个问题,所以我来求助。
在我的Python模块里,有很多日志信息分散在各个地方。我希望调用这个模块的代码能够通过以下方式设置调试级别:
module.DEBUG = INFO
例如。但我不知道怎么把这个变成可用的代码。我有一个全局变量“DEBUG”,我希望在下面的代码行中把它当作变量来用,而不是把DEBUG当成一个普通的字符串,这就是我觉得现在发生的情况:
logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)
我该怎么做才能让这个字符串被当作变量,而不是普通的字符串呢(如果真的是这样的话)?
谢谢!
--Matt
1 个回答
7
如果你希望调用你模块的代码能够控制日志的记录级别,你可以考虑在你的模块中接受日志级别作为一个参数。下面是一些示例代码,展示了你可以怎么做:
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()