python 合并当天tomcat异常日志

简介:

上次使用sftp.get同步远程目录,现在需要用python合并日志

别人很早就写出来了

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
收集Tomcat异常日志并发送邮件
http: / / linux5588.blog. 51cto .com / 65280 / 1208951
#!/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  SMTP
from  email  import  MIMEText
from  email  import  Header
from  os.path  import  getsize
from  sys  import  exit
from  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  =  '/home/back/catalina.out'
  
#该文件是用于记录上次读取日志文件的位置,执行脚本的用户要有创建该文件的权限
last_position_logfile  =  '/home/back/last_position.txt'
error_list_logfile = '/home/back/error_list.txt'
  
#匹配的错误信息关键字的正则表达式
pattern  =  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)
  
def  writeToTxt(list_name,file_path):
     try :
         fp  =  open (file_path, "w+" )
         for  item  in  list_name:
             fp.write( str (item) + "\n" )
         fp.close()
     except  IOError:
         print ( "fail to open file" )
  
#调用发送邮件函数发送邮件
error_info  =  analysis_log(tomcat_log)
writeToTxt(erro_info,error_list_logfile)

自己模仿写的

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python
# coding=utf-8
from  smtplib  import  SMTP
from  email  import  MIMEText
from  email  import  Header
from  os.path  import  getsize
from  sys  import  exit
from  re  import  compile , IGNORECASE
import  os
 
 
#定义主机 帐号 密码 收件人 邮件主题
smtpserver  =  'smtp.163.com'
sender  =  '帐号/发件人'
password  =  '密码'
receiver  =  ( '收件人1' , '收件人2' ,)
subject  =  u 'Web服务器Tomcat日志错误信息'
From  =  u 'xxx Web服务器'
To  =  u '服务器管理员'
 
#定义tomcat日志文件位置
tomcat_log  =  '/home/python/12/'
 
#该文件是用于记录上次读取日志文件的位置,执行脚本的用户要有创建该文件的权限
last_position_logfile  =  '/home/python/last_position.txt'
error_list_logfile = '/home/python/error_list.txt'
 
#匹配的错误信息关键字的正则表达式
pattern  =  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 , 'a' )
         data.write( str (last_positon)  +  '\n' )
         #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)
     last_position  =  0
     this_postion  =  getsize( file )
     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)
 
def  writeToTxt(list_name,file_path):
     try :
         fp  =  open (file_path, "w+" )
         for  item  in  list_name:
             fp.write( str (item) + "\n" )
         fp.close()
     except  IOError:
         print ( "fail to open file" )
 
def  walk(local_dir):
     for  root, dirs, files  in  os.walk(local_dir):
         for  filespath  in  files:
             #return filespath
             local_file  =  os.path.join(root,filespath)
             #error_info2 = analysis_log('/home/python/12/xx.log')
             #print error_info2
             error_info  =  analysis_log(local_file)
             fp  =  open (error_list_logfile, "a+" )
             fp.write(error_info)
 
if  __name__  = =  '__main__' :
     walk(tomcat_log)
     #调用发送邮件函数发送邮件
     #error_info = analysis_log(tomcat_log)
     #writeToTxt(error_info,error_list_logfile)
     #fp = open(error_list_logfile,"w+")
     #fp.write(str(error_info))

第二版

生成zabbix监控,只是监控异常数量,没有过滤exception

  1. 先执行第一个脚本,生成数据

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# !/usr/bin/env python
#-*-coding:utf-8-*-
import  os
import  sys
import  time
import  datetime
import  string
from  smtplib  import  SMTP
from  email  import  MIMEText
from  email  import  Header
from  os.path  import  getsize
from  sys  import  exit
from  re  import  compile , IGNORECASE
  
tomcat_log  =  '/home/logs/'
last_position_logfile  =  '/home/back/test/last_position.txt'
error_list_logfile  =  '/home/back/test/error_list.txt'
pattern  =  compile (r 'Exception|^\t+\bat\b' , IGNORECASE)
fp  =  open (error_list_logfile,  "w+" )
def  writeToTxt(list_name, file_path):
     try :
         fp  =  open (file_path,  "a+" )
         for  item  in  list_name:
             fp.write( str (item)  +  "\n" )
         fp.close()
     except  IOError:
         print ( "fail to open file" )
  
  
# 分析文件找出异常的行
def  analysis_log( file ):
     #parent_file = os.path.dirname(file)
     error_list  =  []
     try :
         data  =  open ( file 'r' )
     except :
         exit()
     for  line  in  data:
         if  pattern.search(line):
             error_list.append( file )
                         break
         data.close()
         if  len (error_list) = = 1 :
             #return ''.join(error_list)
             writeToTxt(error_list,error_list_logfile)
         #return error_list
         #if errors_list == 1:
             #print "%s num is %d" %(file,errors_list)
     #print ''.join(errors_list)
  
def  walk(local_dir):
     for  root, dirs, files  in  os.walk(local_dir):
         for  filespath  in  files:
             # return filespath
             local_file  =  os.path.join(root, filespath)
             # print error_info2
             error_info  =  analysis_log(local_file)
def  walk_dir(home_dir):
     homedir = []
         for  root, dirs, files  in  os.walk(home_dir):
             for  dirname  in  dirs:
                         local_dir  =  os.path.join(root, dirname)
                         now  =  datetime.datetime.now()
                         strdatetime  =  now.strftime( "%Y/%m/%d" )
                         Date = now.strftime( "%d" )
                         #print "Date is %s" %Date
                         result  =  string.find(local_dir,strdatetime)! = - 1
                         if  result:
                             #print local_dir.count('/')
                             if  local_dir.count( '/' ) = = 8 :
                                 homedir.append(local_dir)
         return  homedir
  
if  __name__  = =  '__main__'
     tomcat_last_dir = walk_dir(tomcat_log)
     for  in  tomcat_last_dir:
         walk(i)

2.zabbix脚本两个

python以后都可以这样写

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
# !/usr/bin/env python
#-*-coding:utf-8-*-
import  json
import  os
import  sys
import  time
import  datetime
import  string
from  smtplib  import  SMTP
from  email  import  MIMEText
from  email  import  Header
from  os.path  import  getsize
from  sys  import  exit
file  =  '/home/back/test/error_list.txt'
error_list = []
service = []
try :
     data  =  open ( file 'r' )
except :
     exit()
for  line  in  data:
     error_list.append(line.split( '/' )[ 8 ])
     #service.append(line.split('/')[3])
news_error_list  =  list ( set (error_list))
#news_service = list(set(service))
#print news_error_list
#print news_service
javas = []
for  in  news_error_list:
     javas.append({ '{#EXCEPTION}' :x.strip( '\n' )})
print  json.dumps({ 'data' :javas},indent = 4 ,separators = ( ',' , ':' ))
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
# !/usr/bin/env python
#-*-coding:utf-8-*-
import  json
import  os
import  sys
import  time
import  datetime
import  string
from  smtplib  import  SMTP
from  email  import  MIMEText
from  email  import  Header
from  os.path  import  getsize
from  sys  import  exit
file  =  '/home/back/test/error_list.txt'
error_list = []
try :
     data  =  open ( file 'r' )
except :
     exit()
for  line  in  data:
     error_list.append(line.split( '/' )[ 8 ])
news_error_list  =  list ( set (error_list))
if  len (sys.argv)  = =  2 :
     argv1  =  sys.argv[ 1 ]
     print  error_list.count(argv1)
else :
     print  - 1

标记一些常用写法

result = string.find(local_dir,strdatetime)!=-1

news_error_list = list(set(error_list))

print error_list.count(argv1)

python将数组写入文件

fp = open(error_list_logfile,"w+")

fp.write(str(error_info))

这些脚本,主要的作用就是针对每个文件,过滤带有exception的文件并在grafana显示。



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1861459,如需转载请自行联系原作者

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
相关文章
|
运维 监控 算法
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
MSET-SPRT是一种结合多元状态估计技术(MSET)与序贯概率比检验(SPRT)的混合框架,专为高维度、强关联数据流的异常检测设计。MSET通过历史数据建模估计系统预期状态,SPRT基于统计推断判定偏差显著性,二者协同实现精准高效的异常识别。本文以Python为例,展示其在模拟数据中的应用,证明其在工业监控、设备健康管理及网络安全等领域的可靠性与有效性。
1346 13
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
|
9月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
1644 5
|
12月前
|
运维 监控 安全
Syslog 日志分析与异常检测技巧
系统日志蕴含设备运行关键信息,但分析提取颇具挑战。本文详解从命令行工具(如 Grep、Tail、Awk)到专业软件(如 EventLog Analyzer)的全流程日志分析技巧,助你高效挖掘 Syslog 价值,提升运维与安全响应能力。
700 4
|
人工智能 C# Python
处理python异常
本文介绍了Python中的异常处理机制,并实现了一个简单的异常装饰器。通过`try/except`语句捕获异常,结合`finally`子句完成清理工作。为进一步优化代码结构,文章提出了使用装饰器处理异常的方法,避免函数中大量冗长的异常处理语句。通过类封装异常装饰器,多个函数可共享异常处理逻辑,提升代码简洁性和可维护性。总结强调了装饰器在异常处理中的优势,使代码更加优雅高效。
285 27
|
Java 应用服务中间件 Linux
Tomcat运行日志字符错乱/项目启动时控制台日志乱码问题
总结: 通过以上几种方法,概括如下:指定编码格式、设置JVM的文件编码、修改控制台输出编码、修正JSP页面编码和设置过滤器。遵循这些步骤,你可以依次排查和解决Tomcat运行日志字符错乱及项目启动时控制台日志乱码问题。希望这些建议能对你的问题提供有效的解决方案。
2275 16
如何处理python的常见异常问题
在Python语言中,python异常处理机制主要依赖try、except、else、finally和raise五个关键字。本篇文章将为大家详细讲解一下如何处理python的常见异常问题。
|
人工智能 Shell 开发工具
[oeasy]python065python报错怎么办_try_试着来_except_发现异常
本文介绍了Python中处理异常的基本方法,重点讲解了`try`和`except`的用法。通过一个计算苹果重量的小程序示例,展示了如何捕获用户输入错误并进行处理。主要内容包括: 1. **回顾上次内容**:简要回顾了Shell环境、Python3游乐场和Vim编辑器的使用。 2. **编写程序**:编写了一个简单的程序来计算苹果的总重量,但发现由于输入类型问题导致结果错误。 3. **调试与修正**:通过调试发现输入函数返回的是字符串类型,需要将其转换为整数类型才能正确计算。
465 32
|
监控 Java 应用服务中间件
Tomcat log日志解析
理解和解析Tomcat日志文件对于诊断和解决Web应用中的问题至关重要。通过分析 `catalina.out`、`localhost.log`、`localhost_access_log.*.txt`、`manager.log`和 `host-manager.log`等日志文件,可以快速定位和解决问题,确保Tomcat服务器的稳定运行。掌握这些日志解析技巧,可以显著提高运维和开发效率。
1723 13
|
数据库 Python
[oeasy]python066_如何捕获多个异常_try_否则_else_exception
本文介绍了Python中`try...except...else`结构的使用方法。主要内容包括: 1. **回顾上次内容**:简要复习了`try`和`except`的基本用法,强调了异常处理的重要性。 2. **详细解释**: - `try`块用于尝试执行代码,一旦发现错误会立即终止并跳转到`except`块。 - `except`块用于捕获特定类型的异常,并进行相应的处理。 - `else`块在没有异常时执行,是可选的。 3. **示例代码**:通过具体例子展示了如何捕获不同类型的异常(如`ValueError`和`ZeroDivisionError`),并解释了异常处理
289 24
|
SQL druid Oracle
【YashanDB知识库】yasdb jdbc驱动集成druid连接池,业务(java)日志中有token IDENTIFIER start异常
客户Java日志中出现异常,影响Druid的merge SQL功能(将SQL字面量替换为绑定变量以统计性能),但不影响正常业务流程。原因是Druid在merge SQL时传入null作为dbType,导致无法解析递归查询中的`start`关键字。

推荐镜像

更多