Python日志记录-如何检查记录仪是否为空 [英] Python Logging - How To Check If Logger Is Empty

查看:58
本文介绍了Python日志记录-如何检查记录仪是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在我的应用中实现了日志记录,我想知道是否有一种方法可以检查记录器是否为空.

I just implemented logging in my app, and I'd like to know if there's a method to check if a logger is empty or not.

我要记住的是在脚本中设置两个处理程序:

What I have in mind is to set two handlers in my script:

  • 一个级别为 WARNING
  • 的控制台
  • 一个用于级别为 DEBUG
  • 的文件

在脚本末尾,我需要检查 CONSOLE 记录器是否为空.这意味着在运行期间,记录了一些 level> = WARNING 的消息,在这种情况下,我想通过 smtp 发送调试级别的日志文件.到我的邮箱.

At the end of the script, I need to check if CONSOLE logger is not empty. This means that during the run, some messages with level >= WARNING were logged, and in this case I'd like to send the log file with debug level thru smtpto my mailbox.

是否可以在 python 脚本本身内部进行此检查,而无需将Shell重定向到文件?

Is this check possible inside the python script itself, without shell redirection to file?

推荐答案

有一种通用的方法可以计算使用装饰器调用函数的次数,您可以查看

There's a general purpose way to count the number of times a function was called using decorators you can check out here

如果将此装饰器包装在类调用周围,那么您可能会对每个成员函数被调用的次数感兴趣,如下所示:

If you wrap this decorator around class calls you are interested in you could find out how many times each member function was called, something like this:

def counted(fn):
    def wrapper(*args, **kwargs):
        wrapper.called += 1
        return fn(*args, **kwargs)
    wrapper.called = 0
    wrapper.__name__ = fn.__name__
    return wrapper

class MyLogger(logging.Logger, object):

    @counted
    def info(self, *args, **kwargs):
        super(MyLogger, self).info(*args, **kwargs)

    @counted
    def warning(self, *args, **kwargs):
        super(MyLogger, self).warning(*args, **kwargs)

接下来,只需像其他任何方式一样设置记录器并像往常一样使用它即可:

Next just set up your logger like any other and use it as you normally would:

log = my_logger.MyLogger('test_logger')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)
log.setLevel(logging.DEBUG)

>>> log.info('no big deal')
no big deal
>>> log.info('harmless message')
harmless message
>>> log.warning('oh no')
oh no

>>> log.info.called
2
>>> log.warning.called
1

您需要装饰所有要计数的类,因此需要进行异常,调试等.

You would need to decorate all of the classes you wanted counted, so exception, debug etc.

这篇关于Python日志记录-如何检查记录仪是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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