Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 584b69d456 |
+44
@@ -0,0 +1,44 @@
|
||||
import json
|
||||
import os
|
||||
def analyze_log(filepath):
|
||||
d={
|
||||
"total":0,
|
||||
"by_level":{},
|
||||
"by_user":{},
|
||||
"last_error":None
|
||||
}
|
||||
if not os.path.exists(filepath):
|
||||
return d
|
||||
try:
|
||||
f=open(filepath,'r',encoding='utf-8')
|
||||
lines=f.readlines()
|
||||
except:
|
||||
return d
|
||||
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line =="":
|
||||
continue
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except:
|
||||
continue
|
||||
|
||||
d["total"]+=1
|
||||
|
||||
lvl=data["level"]
|
||||
usr=data["user"]
|
||||
|
||||
if lvl not in d["by_level"]:
|
||||
d["by_level"][lvl]=0
|
||||
d["by_level"][lvl]=d["by_level"][lvl]+1
|
||||
|
||||
if usr not in d["by_user"]:
|
||||
d["by_user"][usr]=0
|
||||
d["by_user"][usr]=d["by_user"][usr]+1
|
||||
|
||||
if lvl == "ERROR":
|
||||
d["last_error"]=data["message"]
|
||||
|
||||
f.close()
|
||||
return d
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
from main import analyze_log
|
||||
f = open("app.jsonl","w",encoding="utf-8")
|
||||
f.write('{"timestamp": "2026-10-01 10:23:45", "level": "INFO", "message": "用户登录成功", "user": "张三"}\n')
|
||||
f.write('{"timestamp": "2026-10-01 10:24:01", "level": "ERROR", "message": "数据库连接失败", "user": "李四"}\n')
|
||||
f.write('随便写的\n')
|
||||
f.write('{"timestamp": "2026-10-01 10:27:00", "level": "INFO", "message": "任务完成", "user": "王五"}\n')
|
||||
f.close()
|
||||
|
||||
res=analyze_log("app.jsonl")
|
||||
print("总数:",res["total"])
|
||||
print("级别统计:",res["by_level"])
|
||||
print("用户统计",res["by_user"])
|
||||
print("最后一条错误:",res["last_error"])
|
||||
Reference in New Issue
Block a user