python日志记录:当级别> =错误时,将整个日志文件作为附件通过电子邮件发送 [英] python logging: email entire log file as attachment when level >= ERROR

查看:39
本文介绍了python日志记录:当级别> =错误时,将整个日志文件作为附件通过电子邮件发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My logging system has a few handlers, log file (INFO), an email handler (>ERROR), and a stream handler for optional debugging. When an error/exception/critical message occurs, I want the email handler to attach the log file from the file handler to the error email.

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

I found this example, but it's basically writing the handler from scratch. https://gist.github.com/LavinJ/238ccb229ac594a50b0a

如果有更简单的方法来修改现有的SMTPHandler,我会很乐意

I'd love if there was a simpler means of modifying the existing SMTPHandler

推荐答案

看源代码,看来这是最简单的方法.单独附加日志文件可与此处理程序和上面的代码很好地配合

Looking at the source, it appears this is the easiest way to do it. Attaching the log file alone works well with this handler and the above code

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)

这篇关于python日志记录:当级别> =错误时,将整个日志文件作为附件通过电子邮件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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