Python - 提取日志作业
作业:读取已有的 testlog.txt 日志,提取免费小说app相关的 Exception,过滤不相干的信息。日志文件:testlog.txt (见文末)
具体要求:
写一个函数,将日志中所有 com.kmxs.reader 进程相关的 exception 日志截取出来(先匹配 Expection ,然后查找后续的Java 堆栈信息(at XXXXXX....),如果 exception 或 堆栈信息中有一行包含 com.kmxs.reader ,即需要将 exception 这一行开始,把所有相关的堆栈信息都提取出来),保存到一个新的文件;
代码如下:
# coding:utf-8 def find_log(L): for index, value in enumerate(L): if 'Exception' not in value: pass else: x = index list = L[x+1:] for index, value in enumerate(list, start=1): if ' at ' in value: pass else: y = index c = L[x:x+y] d = ''.join(c[::]) if 'com.kmxs.reader' in d: with open('jodie_log.txt', 'a+', encoding='utf-8') as f: f.writelines(c) f.write('\n') f.close() return find_log(L[x+y:]) break if __name__ == '__main__': with open('testlog.txt', 'r', encoding='utf-8') as file: L = file.readlines() L.append('aaaaaa') find_log(L)
提取后的结果:
jodie_log.txt Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:658)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:810)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:883)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:844)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423
......