![](/img/trans.png)
[英]How to analyze a .log file by using python and pandas to save into a data framework?
[英]How to analyze a .log file by using python and pandas to save into a data framework?
我正在處理來自一台自動售貨機的一個示例日志文件。 (對熊貓來說很新)。 每天機器都會生成一個.log文件。
Q:如何使用python和pandas從.log文件中提取信息,並最終保存到數據框架中進行下一步分析? 像下面的模式。 (注:消息信息也應該是完整的一條信息)
您可以在下面找到我的示例代碼和 sample.log 文件:
import pandas as pd
filePath = "~/sample.log"
with open(filePath,'r',encoding='utf16') as fp :
line = fp.read()
print(lines)
從上面的示例中,我們可以清楚地看到日志文件包含多個相似的模式信息。 日志文件以 Index 開頭,以 UserName 結尾。
注意到幾件事:
以下是我的一些想法:
分析上述日志最困難的部分是“消息”部分,它也可以有冒號。
日志文件正在重復從 Index、EntryTpye ..... 直到 Message 的過程。
有人可以給我一些代碼來解決這個問題嗎?
太感謝了!
試試這個代碼:
import pandas as pd
filePath = "logtxt.log"
lines = []
with open(filePath,'r') as fp :
lines = fp.readlines()
df = pd.DataFrame()
dict = {}
lastname = ""
for line in lines:
if line and line.strip():
if ( line[0].isspace() ):
value = value + line
dict[name] = value
else:
if ( line.find(':') != -1 ):
name, value = line.split(':', 1)
name = name.strip()
value = value.strip()
dict[name]=value
if ( name == 'UserName' ):
df = df.append(dict, ignore_index=True)
print(df)
使用您給定的輸入文件,它會生成 output 為:
Index EntryType InstanceId Message ... Source TimeGenerated TimeWritten UserName
0 112078 Error 21224490 this is can be a sample test info for machine ... ... unknown 12/11/2020 15:02:20 PM 12/11/2020 15:03:20 PM
1 112079 Error 21224500 this is can be a sample test info for machine ... ... event1 12/11/2020 16:03:20 PM 12/11/2020 16:02:21 PM
[2 rows x 11 columns]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.