我还没有完全掌握 Python 的窍门,无法自己解决这个问题,所以我正在寻求帮助。
我的 python 模块中散布着各种日志消息。我希望调用模块的代码能够通过以下方式设置调试级别:
module.DEBUG = INFO
例如。但我无法将其转化为工作。我有全局变量“DEBUG”,我希望它在下一行中被解释,而不是 DEBUG 充当文字字符串,这就是我认为正在发生的事情:
logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)
如何使该字符串被视为变量而不是文字(如果发生这种情况?)
谢谢!
--马特
最佳答案
如果您希望调用代码控制模块上的日志记录级别,您应该考虑接受日志级别作为模块中的参数。以下是有关如何执行此操作的一些示例代码:
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()
关于python - 使用变量设置日志记录级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25631011/