使用 SMTPHandler 在 Python 日志记录 MemoryHandler 中整理输出 [英] Collate output in Python logging MemoryHandler with SMTPHandler

查看:29
本文介绍了使用 SMTPHandler 在 Python 日志记录 MemoryHandler 中整理输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将日志记录模块 MemoryHandler 设置为排队调试和 SMTPHandler 目标的错误消息.我想要的是在包含所有调试语句(每行一个)的进程错误时发送电子邮件.我收到的是每条调试消息的单独电子邮件.

I have the logging module MemoryHandler set up to queue debug and error messages for the SMTPHandler target. What I want is for an email to be sent when the process errors that contains all debug statements up to that point (one per line). What I get instead is a separate email for every debug message.

这看起来应该是微不足道的,并且是日志记录包的一部分,但我找不到任何关于它的信息,没有示例,Google 上什么也没有.

This seems like it should be trivial, and part of the logging package, but I can't find anything about it, no examples, nothing on Google.

log = logging.getLogger()
log.setLevel(logging.DEBUG)
debug_format = logging.Formatter("%(levelname)s at %(asctime)s in %(filename)s (line %(lineno)d):: %(message)s")

# write errors to email
error_mail_subject = "ERROR: Script error in %s on %s" % (sys.argv[0], os.uname()[1])
error_mail_handler = logging.handlers.SMTPHandler(SMTP_HOST, 'errors@'+os.uname()[1], [LOG_EMAIL], error_mail_subject)
error_mail_handler.setLevel(logging.ERROR)
#error_mail_handler.setLevel(logging.DEBUG)
error_mail_handler.setFormatter(debug_format)

# buffer debug messages so they can be sent with error emails
memory_handler = logging.handlers.MemoryHandler(1024*10, logging.ERROR, error_mail_handler)
memory_handler.setLevel(logging.DEBUG)

# attach handlers
log.addHandler(memory_handler)
log.addHandler(error_mail_handler)

与此相关:

如果 error_mail_handlermemory_handler 的目标,我是否需要明确地将它添加到记录器中?error_mail_handler 应该设置为 DEBUG 还是 ERROR 目标?当它从 memory_handler 获取时,它甚至需要一个目标吗?

Do I need to add the error_mail_handler to the logger explicitly if it is a target of memory_handler anyway? Should error_mail_handler be set to DEBUG or ERROR target? Does it even need a target when it is being fed from memory_handler?

希望看到解决此问题的任何人的一些工作代码.

Would love to see some working code from anyone who has solved this problem.

推荐答案

您可能想要使用或调整 BufferingSMTPHandler,它位于 这个测试脚本.

You might want to use or adapt the BufferingSMTPHandler which is in this test script.

通常,如果它是已添加到记录器的 MemoryHandler 处理程序的目标,则不需要向记录器添加处理程序.如果您设置处理程序的级别,这将影响处理程序实际处理的内容 - 它不会处理任何低于其级别设置的严重程度.

In general, you don't need to add a handler to a logger if it's the target of a MemoryHandler handler which has been added to a logger. If you set the level of a handler, that will affect what the handler actually processes - it won't process anything which is less severe than its level setting.

这篇关于使用 SMTPHandler 在 Python 日志记录 MemoryHandler 中整理输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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