本文介绍了Python日志记录模块中的SMTPHandler一次发送一封电子邮件.我该如何阻止呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Python的logging
模块发送包含日志的电子邮件.我遇到的问题是,每次我写日志条目时,都会发送一封电子邮件.如何在脚本结束时将日志消息排队并发送一封电子邮件?
I'm attempting to use Python's logging
module to send emails containing logs. The problem that I'm having is that each time I write a log entry, an email is sent. How do I queue the log messages and send a single email at the conclusion of the script?
我觉得它是用emit()
方法完成的,但是我不知道该怎么用.
I have a feeling that it's done with the emit()
method, but I can't figure out how to use it.
import logging, logging.handlers
log = logging.getLogger("mylogger")
log.setLevel(logging.DEBUG)
h2 = logging.handlers.SMTPHandler(mailhost='mailserver',
fromaddr='[email protected]',
toaddrs=['[email protected]'],
subject='The log',
credentials=('user','pwd'),
secure=None)
h2.setLevel(logging.INFO)
h2.setFormatter(f)
log.addHandler(h2)
log.info("Did something")
log.info("Did something else")
log.info("This would send a third email. :-(")
推荐答案
请参见(我针对类似的问题给出).要使用的示例处理程序是此处;您可以使其适应您的要求.
See this answer which I gave for a similar question. An example handler to use is here; you can adapt it to your requirements.
这篇关于Python日志记录模块中的SMTPHandler一次发送一封电子邮件.我该如何阻止呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!