🚀 新規事業

request-logging

最終更新 2026年05月08日 / 40_新規事業/SCALE_Build/カタログ/基本装備集/request-logging.md

構造化リクエストログ

何のために?

何か起きた時 access_log なしだと原因特定不能。

どう実装する?

middleware で {method, path, status, duration_ms, user_id} を console.log。

コード例

export async function middleware(req: NextRequest) {
  const start = Date.now();
  const res = await NextResponse.next();
  console.log(JSON.stringify({
    ts: new Date().toISOString(),
    method: req.method,
    path: req.nextUrl.pathname,
    status: res.status,
    duration_ms: Date.now() - start,
    ip: req.headers.get('x-forwarded-for'),
  }));
  return res;
}