Linux环境下用 Swagger 辅助 API 日志分析
一 核心思路与边界
二 日志采集与规范化
/var/log/myapi/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0644 app app
}
三 在 Swagger UI 侧增强可观测性(可选)
const uiConfig = {
url: '/openapi.json',
requestInterceptor: (req) => {
sendLog({
ts: new Date().toISOString(),
op: 'UI_REQUEST',
method: req.method,
url: req.url,
body: req.body
});
return req;
},
responseInterceptor: (res) => {
sendLog({
ts: new Date().toISOString(),
op: 'UI_RESPONSE',
status: res.status,
duration: res.duration
});
return res;
}
};
SwaggerUI(uiConfig);
四 Linux 下的快速分析与可视化
tail -n 10000 app.log | grep '"status":5' | cut -d'|' -f6 | sort | uniq -c | sort -nrtail -n 50000 app.log | awk -F'|' '$8 > 1000 {print $6,$8}' | sort -k2 -nr | headawk -F'|' '{print $6,$7}' app.log | sort | uniq -c | sort -nrgrep 'trace_id=abc123' app.log | less五 端到端落地流程