#!/usr/bin/python
#-*- coding:utf-8 -*-
#
import os
from os.path import getsize
from sys import exit
from re import compile, IGNORECASE
import sys, getpass
import smtplib
from email.mime.text import MIMEText
tomcat_log = '/data/server/tomcats/'
# 匹配的错误信息关键字的正则表达式
pattern = compile('outofmemoryerror', IGNORECASE)
#定义发送邮件函数
def mail(content):
email_host = 'smmprd@smm-app02.wisers.com'
maillist ='wanglisheng@wisers.com,yangxuejun@wisers.com,taosijun@wisers.com,tanxin@wisers.com,kyleli@wisers.com'
#maillist='tanxin@wisers.com'
me = email_host
msg = MIMEText(content)
msg['Subject'] = 'tomcat OutOfMemory Appear'
msg['From'] = me
msg['To'] = maillist
try:
smtp = smtplib.SMTP('localhost')
smtp.sendmail(me, maillist.split(','), msg.as_string())
smtp.quit()
print ('email send success.')
except smtplib.SMTPException:
print "Error: 无法发送邮件"
#读取上一次日志文件的读取位置
def get_last_position(file):
try:
data = open(file, 'r')
last_position = data.readline()
if last_position:
last_position = int(last_position)
else:
last_position = 0
except:
last_position = 0
return last_position
#写入本次日志文件的读取到的本次位置
def write_this_position(file, last_position):
try:
data = open(file, 'w')
data.write(str(last_position))
data.write('\n' + "Don't Delete This File,It is Very important for Looking Tomcat Error Log !! \n")
data.close()
except:
print "Can't Create File !" + file
exit()
#分析文件找出Outofmemory
def analysis_log(file):
#error_list = []
#try:
# data = open(file, 'r')
#except:
# exit()
for logname in os.listdir(file): #循环多个tomcat的路径
L = os.path.join(tomcat_log, logname)
if os.path.isdir(L):
last_position_logfile = ''.join([L,'/error_last_position.txt']) #拼接记录读取位置路径
last_position = get_last_position(last_position_logfile)
dir_log = ''.join([L,'/logs','/catalina.out'])
if os.path.exists(dir_log):
#print (dir_log)
this_position = getsize(dir_log)
try:
data = open(dir_log, 'r')
except:
continue
if this_position < last_position: #log文件小于上次读取的大小,从log文件开始位置读取(日志重新生成了的情况)
data.seek(0)
elif this_position == last_position: #log文件大小=上次读取大小, (日志没变化)
exit()
elif this_position > last_position: #log 文件大于上次读取的大小,从上次大小位置增量读取
data.seek(last_position) #移动文件读取指针到指定位置
error_list = []
for line in data:
if pattern.search(line):
error_list.append(line)
write_this_position(last_position_logfile, data.tell()) #data.tell()返回文件指针的当前位置, 将位置写入保存文件中
data.close()
#print(error_list)
if len(error_list) != 0:
error_info = str(error_list)
mail(''.join([logname,': ', error_info])) # 调用发送邮件函数发送邮件
#return ''.join(error_list)
analysis_log(tomcat_log)