python 合并当天tomcat异常日志 第二版

简介:

把找出的异常文件,归类到指定目录

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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# !/usr/bin/env python
# coding:utf-8
import  os,sys,tempfile,time,datetime,re
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
now  =  datetime.datetime.now()
strdatetime1  =  now.strftime( "%Y%m%d" )
strdatetime  =  now.strftime( "%Y/%m/%d" )
tomcat_log  =  '/home/logs/'
last_position_logfile  =  '/home/back/test/last_position.txt'
#error_list_logfile = '/home/back/test/error_list.txt'
error_list_logfile1  =  '/home/back/test/error_list'
Date = now.strftime( "%d" )
error_list_logfile  =  error_list_logfile1  +  strdatetime1  +  ".txt"
print  error_list_logfile
errorfile = error_list_logfile
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 )
                         #print error_list
                         #errors_list += 1
                         #print "%s" %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)
                         #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
 
 
 
def  make_ex(errorfile):
     with  open (errorfile) as f:
         exfile  =  []
         exdict  =  {}
         for  in  f.readlines():
             expname  =  i.strip().split( '/' )[ 3 ]
             exname  =  i.strip().split( '/' )[ 8 ]
             # if expname not in exfile:
             #     exfile.append(exname)
             estr  =  i.strip()
             #print estr
             youpattern  =  re. compile ( '/(\w+)/(\w+)/(\w+)' )
             result  =  youpattern.match(estr)
             r1  =  result.group()
             r2  =  "ex/"  +  strdatetime1
             r3  =  exname
             rall  =  [r1, r2, r3]
             # exdict[r1]
             rexall  =  "/" .join(rall)  +  '/'
             #print rexall
             if  not  os.path.exists(rexall):
                 os.makedirs(rexall)
             os.system( 'cp -r %s %s'  %  (estr, rexall))
 
 
def  make_diff_ex(c):
     for  in  c:
         i = str (j)
         expname  =  i.strip().split( '/' )[ 3 ]
         exname  =  i.strip().split( '/' )[ 8 ]
         # if expname not in exfile:
         #     exfile.append(exname)
         estr  =  i.strip()
         #print estr
         youpattern  =  re. compile ( '/(\w+)/(\w+)/(\w+)' )
         result  =  youpattern.match(estr)
         if  result:
             r1  =  result.group()
             r2  =  "ex/"  +  strdatetime1
             r3  =  exname
             rall  =  [r1, r2, r3]
             # exdict[r1]
             rexall  =  "/" .join(rall)  +  '/'
             #print rexall
             if  not  os.path.exists(rexall):
                 os.makedirs(rexall)
             os.system( 'cp -r %s %s'  %  (estr, rexall))
         
 
 
 
 
 
'''
def temps(errorfile):
     tmpfile = tempfile.NamedTemporaryFile(delete=False)
     with open(errorfile,'rw') as f:
         readfile="\n".join(f.readlines)
         tmpfile.write(str(f.readlines()))
         return tmpfile
'''
def  temps(errorfile):
     tmpfile = []
     with  open (errorfile, 'r' ) as f:
         tmpfile.append(f.readlines())
         return  tmpfile
 
 
 
def  list_diff(a, b):
     ret  =  []
     for  in  a:
         if  not  in  b:
             ret.append(i)
     return  ret
 
if  __name__  = =  '__main__' :
     if  not  os.path.exists(errorfile):
         fp  =  open (error_list_logfile,  "w+" )
         tomcat_last_dir  =  walk_dir(tomcat_log)
         for  in  tomcat_last_dir:
             walk(i)
         make_ex(errorfile)
     else :
         a = temps(errorfile)
         fp  =  open (error_list_logfile,  "w+" )
         tomcat_last_dir  =  walk_dir(tomcat_log)
         for  in  tomcat_last_dir:
             walk(i)
         #tmpfiles = []
         b = temps(errorfile)
         c = list_diff(a,b)
         if  c:
             make_diff_ex(c)

本来想用tempfile模块的,还要研究下。




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

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
29天前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
22 1
|
1月前
|
索引 Python
如何使用Python的Pandas库进行数据合并和拼接?
【2月更文挑战第28天】【2月更文挑战第103篇】如何使用Python的Pandas库进行数据合并和拼接?
|
1月前
|
开发者 UED Python
怎么理解python中的错误和异常
怎么理解python中的错误和异常
25 0
|
7天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
45 0
|
15天前
|
开发者 Python
使用python打印异常
Python的try-except用于异常处理,尝试执行try块中的代码,若出现异常,则由except捕获并处理。示例展示了当尝试除以零引发`ZeroDivisionError`时,如何打印异常信息。使用`traceback`模块可获取更详尽的异常堆栈信息。在实际应用中,异常信息应根据需求写入日志或发送给开发者,避免向用户暴露敏感信息。
11 0
|
20天前
|
Python
Python中异常的抛出与捕获
4月更文挑战第3天,Python中的异常是处理错误的方式,当错误发生时,异常被触发,未被捕获则导致程序终止。通过`raise`可手动抛出异常,例如`raise ValueError("Invalid value provided")`或自定义异常。使用`try-except`捕获异常,避免程序意外结束。`try`块包含可能出错的代码,`except`块处理特定异常,`else`子句在无异常时执行,`finally`子句确保清理代码始终执行。
17 2
Python中异常的抛出与捕获
|
1月前
|
存储 数据处理 Python
使用Python批量合并Excel文件的所有Sheet数据
使用Python批量合并Excel文件的所有Sheet数据
33 0
|
1月前
|
数据处理 Python
4种方法用Python批量实现多Excel多Sheet合并
4种方法用Python批量实现多Excel多Sheet合并
33 0
|
1月前
|
消息中间件 测试技术 Python
Python使用多线程解析超大日志文件
Python使用多线程解析超大日志文件
20 0