logging.error()被调用了多少次? [英] How many times was logging.error() called?

查看:158
本文介绍了logging.error()被调用了多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许它不存在,因为我在pydoc中找不到它.但是使用python的日志记录包,有没有一种方法可以查询Logger以查明某个特定函数被调用了多少次?例如,报告了多少错误/警告?

Maybe it's just doesn't exist, as I cannot find it in pydoc. But using python's logging package, is there a way to query a Logger to find out how many times a particular function was called? For example, how many errors/warnings were reported?

推荐答案

日志记录模块似乎不支持此功能.从长远来看,您可能最好创建一个新模块,并通过对现有日志记录模块中的项目进行子类化来添加此功能,以添加所需的功能,但是您也可以使用装饰器轻松实现此行为:

The logging module doesn't appear to support this. In the long run you'd probably be better off creating a new module, and adding this feature via sub-classing the items in the existing logging module to add the features you need, but you could also achieve this behavior pretty easily with a decorator:

class CallCounted:
    """Decorator to determine number of calls for a method"""

    def __init__(self,method):
        self.method=method
        self.counter=0

    def __call__(self,*args,**kwargs):
        self.counter+=1
        return self.method(*args,**kwargs)


import logging
logging.error = CallCounted(logging.error)
logging.error('one')
logging.error('two')
print(logging.error.counter)

输出:

ERROR:root:one
ERROR:root:two
2

这篇关于logging.error()被调用了多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆