释放双眼,带上耳机,听听看~!
java服务有的时候报了OutOfMemory错误后,进程还在哪里。为了即时发现这样的错误,写了这个脚本,用这个脚本定时扫描java服务日志文件的最后500行,如果有OutOfMemory错误,就给指定邮箱发送邮件。邮件内容包括:发生错误的主机和报错的文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 1#!/usr/bin/python
2import string
3import smtplib
4from email.mime.text import MIMEText
5import socket
6import fcntl
7import struct
8
9logFiles = ['file.txt']
10pat = 'OutOfMemory'
11mailserver = 'smtp.163.com'
12username = 'xxxx@163.com'
13password = 'yy'
14from_addr = 'xxxx@163.com'
15to_addr = 'zzzz@sohu.com'
16
17def get_ip_address(ifname):
18 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
19 return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', ifname[:15]))[20:24])
20
21host = get_ip_address('eth0')
22
23def fileScan(file,pattern):
24 logFile = open(file,'r')
25 logStrs = logFile.readlines()
26 logLines = len(logStrs)
27 logStr = str(logStrs[-10:logLines])
28 try:
29 logStat = logStr.index(pattern)
30 if logStat:
31 return 1
32 except ValueError:
33 return 0
34
35 logFile.close()
36
37for f in logFiles:
38 stat = fileScan(f,pat)
39 if stat:
40 msg = MIMEText('Host ip: ' + host + "\r\n" + 'OutOfMemory File: ' + f)
41 msg['Subject'] = 'Java Service OutOfMemory'
42 svr = smtplib.SMTP(mailserver)
43 #svr.set_debuglevel(1) #print debug
44 svr.login(username,password)
45 svr.sendmail(from_addr,to_addr,msg.as_string())
46 svr.close()
47