「使用者說下午三點多付款失敗」——如果日誌只是純文字,你得在好幾台主機上 grep,再靠時間猜哪幾行屬於同一個請求。
結構化日誌
2026-11-30 15:02:11 ERROR payment failed for order 42: card declined
改成 JSON:
{"time":"2026-11-30T15:02:11.482Z","level":"error","msg":"payment failed","order_id":42,"user_id":7,"reason":"card_declined","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","duration_ms":812}
每個欄位都能直接篩選、統計:「過去一小時 reason=card_declined 有幾筆?」「duration_ms 的 P95 是多少?」
追蹤 ID
請求進入系統時產生一個 ID,傳遞到所有下游服務與日誌。W3C Trace Context 定義了標準標頭:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
Node.js 中,可以用 AsyncLocalStorage 讓同一個請求的所有日誌自動帶上追蹤 ID:
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomBytes } from 'node:crypto';
import pino from 'pino';
const als = new AsyncLocalStorage();
const logger = pino({
mixin: () => ({ trace_id: als.getStore()?.traceId }),
});
app.use((req, res, next) => {
const incoming = req.headers.traceparent?.split('-')[1];
const traceId = incoming ?? randomBytes(16).toString('hex');
res.setHeader('X-Trace-Id', traceId);
als.run({ traceId }, next);
});
logger.error({ order_id: 42, reason: 'card_declined' }, 'payment failed');
TIP
把追蹤 ID 放進錯誤回應與 X-Trace-Id 標頭。使用者回報問題時附上這個值,就能直接查到完整的請求過程。
日誌等級
| 等級 | 用途 |
|---|---|
| error | 需要人處理的錯誤 |
| warn | 異常但系統能自行處理,例如重試成功 |
| info | 重要的業務事件:登入、下單、部署 |
| debug | 除錯細節,正式環境預設關閉 |
不要記錄的東西
- 密碼、API 金鑰、存取權杖。
- 完整的信用卡號、身分證字號。
- 未經遮罩的個人資料。
在日誌套件中設定欄位遮罩,比靠每個開發者記得要可靠:
const logger = pino({ redact: ['req.headers.authorization', '*.password', '*.card_number'] });
發表留言