Python分析嵌入式日志小工具开发
背景
数据可度量,无人可值守,问题早发现
功能点
关键字分析 自动压缩LOG 自动发送邮件
代码
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/8/27 09:39 # @Author : 局长 # @Site : # @File : XXX.py # @Software: PyCharm import time import datetime import re import os import sys import platform import zipfile import shutil from time import strftime from SendMail import * def TestLog(file_path): # print('■' * 60) print("-" * 60) print('xxx日志结果统计如下:') print('日志名称:%s' % file_path) print("-" * 60) time_local=time.strftime("%Y-%m-%d", time.localtime()) print('拷机日期:%s' % time_local) log_keywords = {"key":'value', } txt = open(file_path,'r',encoding="utf-8").read() result = {} for key,value in log_keywords.items(): test_text = len(re.findall(key,txt)) print("关键字[ %s ]"%key+ ",%s"%value + ":%s"%test_text) result[value] = test_text
判断语句
判断分析出的日志内容是否有异常,如果有,则进行压缩,并发送邮件,如果没有,就不操作。
if result['重启'] != 0 or result['重启且未恢复'] != 0: print("WiFi有重启异常,Watchdog重启次数为:%s 次。\n重启未恢复次数为:%s 次。\n日志将通过邮件方式送达你的邮箱,请查收!" % (result['重启次数'],result['重启且未恢复(关闭了watchdog)'])) print("RX重置次数为%s 次"%result['UVC重置,RX重启']) # 压缩日志文件 ZipLogFiles() # AutoSend_Mail() elif result['UVC重置,RX重启'] != 0: print("RX程序有重启异常,重启次数为:%s 次。\n日志将通过邮件方式送达你的邮箱,请查收!" % result['UVC重置,RX重启']) for i in range(n,n+1): #不再重复执行压缩文件+邮件发送,跳出 if i == 0: ZipLogFiles() # AutoSend_Mail() break print("检测已发过日志邮件,不进行二次发送!") else: xunluoTime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("巡检时间:%s 未发现程序崩溃异常,巡检继续进行..."%xunluoTime)
压缩日志
###对问题日志进行压缩处理 """定义全局变量""" logsdir = r"C:\Users" # 表示当前文件路径 compressPathName = r"C:\Users\问题日志.zip" n = 0 def ZipLogFiles(): ### 压缩 """声明全局变量""" global logsdir,compressPathName,n logsdir = logsdir # 表示当前文件路径 compressPathName = compressPathName zip_file = zipfile.ZipFile(compressPathName, 'w', zipfile.ZIP_DEFLATED) # 遍历文件夹下的所有.log文件,并进行压缩 for files in os.listdir(logsdir): if files.endswith(".log"): file_path = os.path.join(logsdir, files) # 会返回压缩包内所有文件名的列表 zip_file.write(file_path, files) # 将文件写入zip压缩文件——正常压缩,不出现多层目录 zip_file.close() print("压缩完成!") n+=1
调用执行
可以对执行代码进行定时巡航。
import time # from QVZipMailTest import * from QVLogTest import * AutoTestTime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) t = 1 while t < 100: print("自动执行时间:%s 开始进行第%s次自动化测试!"%(AutoTestTime,n)) TestLog(file_path_1=r'C:\Users\xxx.log') # WiFi替换路径即可 t+=1 time.sleep(3600)
邮件自动发送的就不展示了,关注公众号「测试情报局」后台回复「关键字分析」,可以获取全部源码。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战