python分析日志

本身是打算使用shell写的,awk不太熟悉(后续有时间再使用shell写一个;正好环境改到linux上了,安装了python,所以就先用python写一个可以使用的。)

ddl.log有如下信息:需要将SQLSTATE=xxxxx(xxxxx不等于42750)这一行数据输出到另一个文本中。

name "XXXXCH" of type "SCHEMA".  SQLSTATE=42710

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import os
import time

SQLSTATE = "SQLSTATE="
line_no=1

url_result = r'/home/pi/Documents/pythonspace/log_analysis/ddl_state.log'

file_ddl_state = open(url_result, "w")

state_other_lines=[]
state_42710_lines=[]

with open(r"/home/pi/Documents/pythonspace/log_analysis/ddl.log", "r") as f:
    while(True):
        line = f.readline()
        if not line:
            break
        print(line)
        index=line.find(SQLSTATE)
        if index > -1:
            sqlstate=line[index+len(SQLSTATE):-1]
            # print(sqlstate)
            if '42710' != sqlstate:
                state_other_lines.append(str(line_no)+":"+line)
            else:
                # print(line)
                state_42710_lines.append(str(line_no)+":"+line)
        line_no+=1

try:
    for other_state in state_other_lines:
        file_ddl_state.write(other_state)
    file_ddl_state.flush
except:
    file_ddl_state.close()
finally:
    file_ddl_state.close()
        


 

你可能感兴趣的:(python分析日志)