在 Linux 下“解析 JS 日志”通常分为几种场景:
下面按常见用法给你一个系统性的解析思路。
先确认日志类型:
head -n 20 app.log
常见格式有:
grep -i "error\|exception\|undefined\|TypeError" app.log
grep "2024-01-21 10:" app.log
tail -f app.log
TypeError: Cannot read properties of undefined
Error: connect ECONNREFUSED
UnhandledPromiseRejectionWarning
提取堆栈:
grep -A 10 "TypeError" app.log
jq 解析 JSON 日志(推荐)如果日志是:
{"level":"error","msg":"db failed","stack":"..."}
解析:
jq 'select(.level=="error")' app.log
只看消息:
jq -r '.msg' app.log
如果是浏览器上报到服务器的日志:
jq -r '{url:.url, error:.error}' logs.json
jq -r '.error' app.log | sort | uniq -c | sort -nr
import json
with open("app.log") as f:
for line in f:
try:
data = json.loads(line)
if data.get("level") == "error":
print(data.get("msg"))
except:
pass
console.log,用 winston / pino如果你能发一段真实日志样例(脱敏后),我可以直接帮你写精准的解析命令或脚本。