[英]How can I get an array of all possible log levels?
I wish to get all possible, current, log levels in the application.我希望获得应用程序中所有可能的当前日志级别。 I am using the standard logging library for python 2.7.我正在使用 python 2.7 的标准日志记录库。
Something along the lines of:类似的东西:
logging.getLevels()
[DEBUG, INFO, WARNING, ERROR, CRITICAL]
My use case for this, would be to pass it into argsparse.我的用例是将它传递给 argsparse。 We define some custom log levels in our application, and it would be nice for those to automatically propagate into argparse.我们在我们的应用程序中定义了一些自定义日志级别,这些级别自动传播到 argparse 会很好。
parser = argparse.ArgumentParser('our app')
parser.add_argument('-l', '--loglevel', type=str, help='Log level',
choices=logging.getLevels(), default='WARNING')
I can't find a function like this in the documentation .我在文档中找不到这样的 function。 The closest I can find is getLevelName(int level) which will return the string based off an integer.我能找到的最接近的是 getLevelName(int level),它将返回基于 integer 的字符串。
Following on from the question @ymbirtt linked, I worked out this: It calls the _levelNames and then traverses it making only to get the string answers. 继@ymbirtt链接的问题之后,我解决了这个问题:它调用_levelNames然后遍历它只是为了得到字符串的答案。
[v for (k,v) in logging._levelNames.iteritems() if type(k) is int]
In python 3: 在python 3中:
[v for (k,v) in logging._levelNames.items() if type(k) is int]
In the finished solution: 在完成的解决方案:
parser.add_argument('-l', '--loglevel', type=str, help='Log level',
choices=[v for (k,v) in logging._levelNames.iteritems() if type(k) is int],
default='WARNING')
Edit: Swapped value and key around keeps ordering 编辑:交换值和键周围保持订购
Maybe a shorter solution can be:也许更短的解决方案可以是:
list(logging._levelToName.values())
# ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.