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

标签 python logging xdebug

我还没有完全掌握 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/

相关文章:

python - Pandas 聚合然后得到组平均值

python - 如何使用python请求获取网站的服务器信息?

python - python 中的多线程 : is it really performance effiicient most of the time?

安卓日志 'GC_EXTERNAL_ALLOC' 'GC_FOR_MALLOC'

linux - 管理 cron 作业创建的日志文件

php - 在 Windows 上将 Xdebug 和 PhpStorm 与 Docker 容器一起使用

python - 如何使用 Python 创建 PNG 模板

oracle - 如何在oracle 10g 中为存储过程创建错误日志?

xdebug - 如何启用格式化的Xdebug错误和跟踪

debugging - PhpStorm在调试器中退后一步