首页 > 代码库 > 分析错误日志,发送邮件通知

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

# -*- 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 = [‘111111111111@qq.com‘, ‘2222222222@qq.com‘]
SMTP_SERVER = ‘smtp.exmail.qq.com‘
ACCOUNT = ‘hehe@qq.com‘
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()

  

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