实用:Python 自动化实现超强大的日志分析功能

需求背景

日志量级比较大,又没有统一的收集工具,同时又想要去分析日志里面长耗时的接口,这种情况下该如何实现这个功能呢?

下面将使用 Python 代码具体实操来解决这个问题。

Python代码实操

以下代码实用性很强,建议感兴趣的小伙伴逐行阅读,代码逻辑相对较容易。如有疑问,请后台留言~

#coding=utf8
import requests
import json
import os
from collections import Counter

count=0
contentlist=[]
list1=[]


#定义一个通用的post请求方法
def httpPost(uri, data):
    header = {"Content-Type": "application/json"}
    print("----------------------请求" + str(uri) + "接口地址------------------------")
    print(uri)
    print("----------------------请求接口参数------------------------")
    print(data)
    resp_content = requests.post(url=uri, headers=header, verify=False, json=data)
    resp_content = json.loads(resp_content.content)
    print("---------------------请求接口返回结果----------------------")
    print(resp_content)
    return resp_content

#定义读取指定日志文件并推送到相应的接口
def readFileAndSendApi(file):
    global count
    list1=[]
    # with open("Ewaresoft.FOne-"+dates+".log.Info",encoding="utf-8") as f:
    with open(file, encoding="utf-8") as f:
        while(True):
            content=f.readline()
            # print(content)
            if(not content):
                break
            else:
                if("Total execution time" in content):
                    count+=1
                    createtime=content.split(" Ewaresoft")[0].split("时间:")[1]
                    host_name=content.split("http://")[1].split("/")[0]
                    api_name=content.split("http://")[1].split("5002")[1].split(" ")[0]
                    method_type=content.split("http://")[1].split(" ")[1].split(",")[0]
                    waste_time = content.split("time: ")[1].replace("\n", "").replace(" ", "").split(":")[1:]
                    waste_time=float(waste_time[1])
                    if(waste_time>5):
                        if (float(content.split("time: ")[1].replace("ms", "")) > float(2000)):
                            waste_time=content.split("time: ")[1].replace("ms", "").replace("\n","").replace(" ","")
                            datas={"createtime":createtime,"host_name":host_name,"api_name":api_name,"method_type":method_type,"waste_time":waste_time}
                            dealContent(datas)
                            print(datas)
                            list1.append(datas)
    print(list1)
    list1.sort(key=lambda x:x["waste_time"])
    print("*"*10)
    for i in list1:
        print(i)

#调用接口将数据推送到日志收集平台
def dealContent(data):
    httpPost("http://10.10.1.242:5555/addXserviceApi",data)

#读取日志文件,追加放入列表
def readFile(files):
    with open(files,encoding="utf-8") as f:
        while(True):
            content=f.readline()
            # print(content)
            if(not content):
                break
            else:
                if("Total execution time" in content):
                    api_name=content.split("http://")[1].split("5002")[1].split(" ")[0]
                    list1.append(api_name)

#获取指定目录下的所有日志文件
def get_file(path):
    file_list=[]
    for root,dirs,files in os.walk(path):
        for file in files:
            if(file.endswith("Info")):
                file_list.append(file)
    return file_list

#实时打印日志耗时排序接口
def print_result(files):
    print(files)
    for file in files:
        print(file)
        #调用读取文件的方法
        readFile(file)
        #调用读取文件并推送数据到接口的方法
        readFileAndSendApi(file)
    print(len(list1))
    list2=[]
    for i in list1:
        a=str(i).split("/")
        b="/".join(a[:4])
        list2.append(b)
    print(Counter(list2))
    print(len(dict(Counter(list2))))

if __name__ == '__main__':
    files = get_file("D:\wl\\testproject\Fone")
    print_result(files)

执行结果

执行完成后的数据实时统计如下

Counter({'/api/notice/getNoticeList': 79564, '/api/CheckBoard/GetCheckGroup': 75805, '/api/Voucher/GetVoucherList': 73695,
         '/api/BusinessModel/GetModelInfo': 57266, '/api/Voucher/UpdateOrAddVoucher': 50520...})

接口数据推送后展示如下图

在这里插入图片描述


资源分享

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走…

在这里插入图片描述

​这些资料,对于想从事【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!凡事要趁早,特别是技术行业,一定要提升技术功底。希望对大家有所帮助…….

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值