指令碼功能:
收集Tomcat異常日誌並發送郵件,如果修改Regex,也可以用於收集其他記錄檔的錯誤資訊
運行環境:
Python2.7/2.4皆可運行
指令碼使用方法:
可利用Crontab或者計劃任務來指定時間運行,例如:
*/10 * * * * 指令碼路徑
指令碼運行效果如下:
650) this.width=650;" src="http://www.bkjia.com/uploads/allimg/131228/114223F25-0.png" title="QQ20130524133737.png" />
指令碼內容如下:
#!/usr/bin/env python# coding=utf-8#---------------------------------------------------------# Name: Tomcat錯誤記錄檔發送郵件指令碼# Purpose: 收集Tomcat異常日誌並發送郵件# Version: 1.0# Author: LEO# BLOG: http://linux5588.blog.51cto.com# EMAIL: chanyipiaomiao@163.com# Created: 2013-05-22# Copyright: (c) LEO 2013# Python: 2.7/2.4 皆可使用#--------------------------------------------------------from smtplib import SMTPfrom email import MIMETextfrom email import Headerfrom os.path import getsizefrom sys import exitfrom re import compile, IGNORECASE#定義主機 帳號 密碼 收件者 郵件主題smtpserver = 'smtp.163.com'sender = '帳號/寄件者'password = '密碼'receiver = ('收件者1','收件者2',)subject = u'Web伺服器Tomcat日誌錯誤資訊'From = u'xxx Web伺服器'To = u'伺服器管理員'#定義tomcat記錄檔位置tomcat_log = '/usr/local/tomcat/logs/catalina.out'#該檔案是用於記錄上次讀取記錄檔的位置,執行指令碼的使用者要有建立該檔案的許可權last_position_logfile = '/tmp/last_position.txt'#匹配的錯誤資訊關鍵字的Regexpattern = compile(r'Exception|^\t+\bat\b',IGNORECASE)#發送郵件函數def send_mail(error): #定義郵件的頭部資訊 header = Header.Header msg = MIMEText.MIMEText(error,'plain','utf-8') msg['From'] = header(From) msg['To'] = header(To) msg['Subject'] = header(subject+'\n') #串連SMTP伺服器,然後發送資訊 smtp = SMTP(smtpserver) smtp.login(sender, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.close()#讀取上一次記錄檔的讀取位置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_positon): try: data = open(file,'w') data.write(str(last_positon)) 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()#分析檔案找出異常的行def analysis_log(file): error_list = [] try: data = open(file,'r') except: exit() last_position = get_last_position(last_position_logfile) this_postion = getsize(tomcat_log) if this_postion < last_position: data.seek(0) elif this_postion == last_position: exit() elif this_postion > last_position: data.seek(last_position) for line in data: if pattern.search(line): error_list.append(line) write_this_position(last_position_logfile,data.tell()) data.close() return ''.join(error_list)#調用發送郵件函數發送郵件error_info = analysis_log(tomcat_log)if error_info: send_mail(error_info)
本文出自 “雷納科斯的部落格” 部落格,請務必保留此出處http://linux5588.blog.51cto.com/65280/1208951