python日志记录:当level> = ERROR时,将整个日志文件作为附件发送

时间:2016-04-13 00:23:15

标签: python email logging

我的日志记录系统有一些处理程序,日志文件(INFO),电子邮件处理程序(> ERROR)和用于可选调试的流处理程序。当出现错误/异常/关键消息时,我希望电子邮件处理程序将日志文件从文件处理程序附加到错误电子邮件中。

import logging

def initialize_logging():
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    file_handler = createFileHandler()
    file_handler.setLevel(logging.INFO)
    logger.addHandler(file_handler)

    email_handler = createEmailHandler(file_handler.baseFilename)
    email_handler.setLevel(logging.ERROR)
    logger.addHandler(email_handler)

我找到了这个例子,但它基本上是从头开始编写处理程序。 https://gist.github.com/LavinJ/238ccb229ac594a50b0a

如果有更简单的方法来修改现有的SMTPHandler

,我会很高兴

1 个答案:

答案 0 :(得分:0)

查看来源,看来这是最简单的方法。单独附加日志文件可以很好地处理这个处理程序和上面的代码

class SMTPAttachmentHandler(logging.handlers.SMTPHandler):
    def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None,
                 secure=None, attachment=None):
        super(SMTPAttachmentHandler, self).__init__(mailhost, fromaddr, toaddrs, subject,
                                                    credentials, secure)
        self.attachment = attachment

    def emit(self, record):
        if self.attachment is None or not os.path.isfile(self.attachment):
            return super(SMTPAttachmentHandler, self).emit(record)
        try:
            import smtplib
            from email.utils import formatdate
            from email.mime.text import MIMEText
            from email.mime.multipart import MIMEMultipart

            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout)

            msg = MIMEMultipart()
            msg['From'] = self.fromaddr
            msg['To'] = ",".join(self.toaddrs)
            msg['Date'] = formatdate()
            msg['Subject'] = self.getSubject(record)
            msg.attach(MIMEText(self.format(record).encode('utf-8'), 'html', 'utf-8'))

            dispo = 'attachment; filename="%s"' % os.path.basename(self.attachment)
            with open(self.attachment, "rb") as fd:
                attachment = MIMEText(fd.read())
                attachment.add_header("Content-Disposition", "attachment",
                                      filename=os.path.basename(self.attachment))
                msg.attach(attachment)

            if self.username:
                if self.secure is not None:
                    smtp.ehlo()
                    smtp.starttls(*self.secure)
                    smtp.ehlo()
                smtp.login(self.username, self.password)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg.as_string())
            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)