分析错误日志,发送邮件通知

Posted 黑色木偶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分析错误日志,发送邮件通知相关的知识,希望对你有一定的参考价值。

# -*- encoding:utf8 -*-
"""
    logger_mail.py
    ~~~~~~~~~~~~~~
    分析每天的错误日志,发送邮件通知

    =====================================B
"""

import sys
import ConfigParser  # 是Python自带的模块, 用来读写配置文件
import smtplib
from datetime import datetime, timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE

reload(sys)
sys.setdefaultencoding(‘utf8‘)

__all__ = [
    ‘send_error_mail‘
]

CONSTANTS_CFG_FILE = ‘/aa/sss/ddd/constants.cfg‘

IGNORE_PREFIX = [‘NOTSET‘, ‘DEBUG‘, ‘INFO‘]
RECEIVERS = [‘[email protected]‘, ‘[email protected]‘]
SMTP_SERVER = ‘smtp.exmail.qq.com‘
ACCOUNT = ‘[email protected]‘
PASSWORD = ‘*****‘

MAIL_TEMPLATE = """
<html >
<head > </head >
<body >
<h1 > {subject} < /h1 >
<p > {content} < p >
</body >
</html >
"""


def _can_ignore(line):
    """不是错误记录忽略"""
    prefix = line[:10]
    prefix = prefix.split(‘|‘)[0].upper()
    return True if prefix in IGNORE_PREFIX else False


def _load_application_log(filename):
    error_msgs = []
    with open(filename) as f:
        for line in f:
            if _can_ignore(line):
                continue
            error_msgs.append(line)
    return error_msgs


def send(subject, content):
    html_mimetext = MIMEText(
        MAIL_TEMPLATE.format(subject=subject, content=content), ‘html‘)

    msg = MIMEMultipart()
    msg[‘From‘] = ACCOUNT
    msg[‘To‘] = COMMASPACE.join(RECEIVERS)
    msg[‘Subject‘] = subject
    msg.attach(html_mimetext)

    smtp = smtplib.SMTP(SMTP_SERVER)
    smtp.login(ACCOUNT, PASSWORD)
    smtp.sendmail(ACCOUNT, RECEIVERS, msg.as_string())
    smtp.quit()


def send_error_mail():
    #从配置中读取日志文件存放路径
    conf = ConfigParser.ConfigParser()
    conf.read(CONSTANTS_CFG_FILE)
    logger_path = conf.get(‘path‘, ‘LOGGER_PATH‘)
    yesterday = (datetime.now() + timedelta(days=-1)).strftime(‘%Y-%m-%d‘)
    filename = ‘{}.{}‘.format(logger_path, yesterday)
    #读取日志文件
    error_logs = _load_application_log(filename)
    subject = ‘ARTPOLLOAPI {} BUG LIST‘.format(
        datetime.now().strftime(‘%Y-%m-%d‘))
    content = ‘<br/>‘.join(
        [
            line if ‘|‘ not in line else ‘<br/>{}‘.format(line)
            for line in error_logs
        ])
    #发送邮件
    return send(subject, content)


if __name__ == ‘__main__‘:
    send_error_mail()

  

以上是关于分析错误日志,发送邮件通知的主要内容,如果未能解决你的问题,请参考以下文章

发送包含节日志信息的电子邮件

Powershell 查看日志并发送电子邮件通知

在不阻止的情况下发送批量通知电子邮件

Android 错误从通知转到片段

Stackdriver 错误电子邮件通知未发送

扫描仪通过SMTP中继服务器发送通知邮件失败