python读取日志匹配日志信息(二)

python读取日志匹配日志信息

一、绪论

1、python获取远程服务器上的日志(远程获取日志连接:python远程连接linux

2、python读取服务器日志,进行分析获取到需要的数据

3、将数据写入到Excel表格 ( python读写Excel )

二、python分析日志

import re
class WcsLog:

    data_all = {}
    data_ev = {}

    print("开始提取。。。")
    with open("../mylog.log") as f:
        count = 0
        newline =''
        #根据正则将匹配到多行数据组成一行日志。
        for line in f.readlines():
            patt = r'.*(ERROR|WARN|INFO).*'
            pattern = re.compile(patt)
            result = pattern.findall(line)
            print("----------------------------",type(result))
            if "" == newline or 0 == len(result):
                newline = newline +" "+ line.strip('\n')  #拼接
                continue
            else :
                #判断当前行中有没有匹配的字符串
                patt = r'.*with=netbeans.*'
                pattern = re.compile(patt)
                #如果当前行匹配到字符串,将改行数据赋值给trsult2,如果没有匹配到将空数组赋值给result2
                result2 = pattern.findall(newline)
                if 0 < len(result2):
                    #对匹配到的数据根据正则方式进行分段。
                    log = re.split("\s", newline)
                    print("-----------------",newline)
                    print("---------------------log类型",type(log))
                    #在分割字符串后,取出需要的数据。
                    data_ev["date"] = log[3]+log[4]
                    data_all[count] = data_ev

                    print("已取出",count,"行")
                    print("匹配到的时间----------------------",data_ev)
                    count += 1
                newline = line.strip('\n')

在上面的基础模板中进行优化,自动读取多个文件进行匹配。将结果保存为对象,对象中包含匹配到的结果和Excel坐标。

import re
import os
class WcsLog:
    #在/home/long/newlog文件夹下遍历所有日志文件
    def allLogs(self,filepath):
        pathDir = os.listdir(filepath)
        childfile = []
        for allDir in pathDir:
            child = os.path.join('%s%s' % (filepath, allDir)).encode('utf-8')
            childfile.append(child)
            print(childfile)
            print(type(childfile))

        return childfile



    def logAnalusis(self,listfile):
        return_data = {}
        print(type(listfile))
        print(listfile)
        for i in listfile:
            files = i
            print(files)
            print("开始提取。。。")
            newline =''
            with open(files) as f:
                count = 1
                #根据正则将匹配到多行数据组成一行日志。
                for line in f.readlines():
                    patt = r'.*(ERROR|WARN|INFO).*'
                    pattern = re.compile(patt)
                    result = pattern.findall(line)
                    print("-----日志第"+str(count)+"行-----------",type(result))
                    if "" == newline or 0 == len(result):
                        newline = newline +" "+ line.strip('\n')  #拼接
                        continue
                    else :
                        return_data =self.match(newline,return_data)
                        newline = line.strip('\n')
                        count += 1
            return_data = self.match(newline, return_data)
        print(return_data)
        return return_data

    def match(self ,newline,return_data):
        patternNum = {
            'a':{
                'match': 'a=netbeans',
                'row':1,
                'col':1,
                'date':""
            },
            'b':{
                'match': 'b=netbeans',
                'row':2,
                'col':1,
                'date':""
            },
            'c':{
                'match': 'c=netbeans',
                'row':3,
                'col':1,
                'date':""
            },
            'd':{
                'match': 'd=netbeans',
                'row':4,
                'col':1,
                'date':""
            },
        }
        for i in patternNum:
            if i in return_data.keys():
                continue
            print('--------------匹配第' + i + '个正则---------------', patternNum[i]['match'])
            data_time = {}

            # 判断当前行中有没有匹配的字符串
            patt = r'.*' + patternNum[i]['match'] + '.*'
            pattern = re.compile(patt)
            # 如果当前行匹配到字符串,将改行数据赋值给trsult2,如果没有匹配到将空数组赋值给result2
            result2 = pattern.findall(newline)
            if 0 < len(result2):
                # 对匹配到的数据根据正则方式进行分段。
                log = re.split("\s", newline)
                print("-------匹配" + i + "成功----------", newline)
                # 在分割字符串后,取出需要的数据。
                data_time["date"] = log[3] + log[4]
                data_time["row"] = patternNum[i]['row']
                data_time["col"] = patternNum[i]['col']
                return_data[i] = data_time

                print("匹配到" + i + "的时间----------------------", data_time)
                break
        return return_data

# tt = WcsLog()
# listfile = tt.allLogs('D:/PythonWorkSpace/newlog/')
# tt.logAnalusis(listfile)
发布了268 篇原创文章 · 获赞 104 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/m0_38039437/article/details/101646057