logging.error() 被调用了多少次?
也许它根本不存在,因为我找不到它。 但是使用 python 的日志记录包,有没有办法查询记录器以找出特定函数被调用的次数? 例如,报告了多少错误/警告?
Maybe it's just doesn't exist, as I cannot find it. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
日志记录模块似乎不支持此功能。 从长远来看,您可能最好创建一个新模块,并通过对现有日志记录模块中的项目进行子类化来添加此功能,以添加您需要的功能,但您也可以使用装饰器轻松实现此行为:
输出:
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:
Output:
您还可以向记录器添加一个新的处理程序来计算所有调用:
然后您可以使用字典来输出调用数。
You can also add a new Handler to the logger which counts all calls:
You can then use the dict afterwards to output the number of calls.
有一个
warnings
模块 -在某种程度上——做了一些这样的事情。您可能希望将此计数功能添加到自定义 Handler 。 问题是有一百万个处理程序,您可能希望将其添加到多个类型中。
您可能想将其添加到过滤器,因为那是独立于正在使用的处理程序。
There'a a
warnings
module that -- to an extent -- does some of that.You might want to add this counting feature to a customized Handler. The problem is that there are a million handlers and you might want to add it to more than one kind.
You might want to add it to a Filter, since that's independent of the Handlers in use.
基于罗尔夫的回答和如何将字典写入文件,这里是另一个将计数存储在 json 文件中的解决方案。 如果 json 文件存在并且
continue_counts=True
,它将恢复初始化时的计数。Based on Rolf's answer and how to write a dictionary to a file, here another solution which stores the counts in a json file. In case the json file exists and
continue_counts=True
, it restores the counts on initialisation.