我想扩展现有的logging.LEVEL
机制,以便我可以选择在DEBUG
,INFO
,ERROR
等不同的日志记录级别之间切换,但是还为每个级别定义depth
。
例如,我们假设日志记录级别设置为logging.DEBUG
。所有log.DEBUG()
来电均可见。
log.debug('Limit event has occurred.')
所以我得到了:
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
我所追求的是将额外的深度级别传递给log.debug()
来电,以便我可以控制DEBUG
消息中打印的详细信息量,而不是完全启用或禁用 DEBUG级别,但控制 debug 消息将携带多少信息。因此,在所有情况下,我们都会看到调试消息,但在某些情况下,它不太详细,在某些情况下会包含更多信息。
例如:
log.debug('Limit event has occurred.', verbosity=1)
log.debug('The following user has caused the limit event: %s' % (user), verbosity=3)
log.debug('The following files have been affected: %s' % [list_of_files], verbosity=7)
因此,当日志记录级别设置为DEBUG
且全局详细程度设置为GLOBAL_VERBOSITY=1
时,我们将得到:
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
如果全局详细程度设置为GLOBAL_VERBOSITY=4
,我们将得到:
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) The following user has caused the limit event: xpr
如果全局详细程度设置为GLOBAL_VERBOSITY=9
,我们将获得所有详细信息:
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) Limit event has occurred.
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) The following user has caused the limit event: xpr
[2016-10-08 10:07:29,807] <__main__> {myApp:test_condition_info:93} (DEBUG) The following files have been affected: ['inside.ini', 'render.so']
我该如何解决这个问题?
答案 0 :(得分:2)
您是否只能使用更细粒度的日志记录级别? DEBUG
只是级别10的包装器。您可以使用
Logger.log(10, "message")
以调试级别登录,然后
Logger.log(9, "message")
不会出现在调试级别,但如果你这样做
Logger.setLevel(9)
如果你已经开始以另一种方式做这件事了,你应该看看&#39;过滤器&#39;。
#!/usr/bin/env python
import logging
GLOBAL_VERBOSITY = 1
class LoggingErrorFilter(logging.Filter):
def filter(self, record):
if record.__dict__.get("verbosity", 0) > GLOBAL_VERBOSITY:
print "Log message verbosity is greater than threshold, logging line:{0}".format(record)
return True
print "Log message verbosity is lower than threshold, not logging line:{0}".format(record)
return False
logging.basicConfig(level=logging.DEBUG, filename="test.log")
logger = logging.getLogger()
filter = LoggingErrorFilter()
logger.addFilter(filter)
def main():
logger.info("Message 1", extra={"verbosity":3})
logger.info("Message 2", extra={"verbosity":1})
if __name__ == "__main__":
main()