添加 q1/main.py

q1 题 main.py
This commit is contained in:
2026-10-03 07:57:29 +08:00
parent b946fb730f
commit ac362fc9ac
+38
View File
@@ -0,0 +1,38 @@
import json
def analyze_log(filepath: str) -> dict:
result = {
"total": 0,
"by_level": {},
"by_user": {},
"last_error": None
}
try:
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
log_data = json.loads(line)
except json.JSONDecodeError:
continue
result["total"] += 1
level = log_data.get("level")
if level:
result["by_level"][level] = result["by_level"].get(level, 0) + 1
user = log_data.get("user")
if user:
result["by_user"][user] = result["by_user"].get(user, 0) + 1
if level == "ERROR":
result["last_error"] = log_data.get("message")
except FileNotFoundError:
pass
return result
if __name__ == "__main__":
res = analyze_log("app.jsonl")
print(res)
print("成功")