Implement structured logging for API routes (P3.7)

Replace console.error with pino structured logger across API routes
and add key event logging per observability spec:
- Auth failure (warn): reason
- Period logged (info): userId, date
- Override toggled (info): userId, override, enabled
- Decision calculated (info): userId, decision, reason
- Error events (error): err object with stack trace

Files updated:
- auth-middleware.ts: Added structured logging for auth failures
- cycle/period/route.ts: Added Period logged event + error logging
- calendar/[userId]/[token].ics/route.ts: Replaced console.error
- overrides/route.ts: Added Override toggled events
- today/route.ts: Added Decision calculated event

Tests: 720 passing (added 3 new structured logging tests)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-11 09:19:55 +00:00
parent 00d902a396
commit 714194f2d3
7 changed files with 124 additions and 12 deletions

View File

@@ -11,6 +11,7 @@ import {
PHASE_CONFIGS,
} from "@/lib/cycle";
import { getDecisionWithOverrides } from "@/lib/decision-engine";
import { logger } from "@/lib/logger";
import { getNutritionGuidance } from "@/lib/nutrition";
import { createPocketBaseClient } from "@/lib/pocketbase";
import type { DailyData, DailyLog, HrvStatus } from "@/types";
@@ -99,6 +100,12 @@ export const GET = withAuth(async (_request, user) => {
// Get training decision with override handling
const decision = getDecisionWithOverrides(dailyData, user.activeOverrides);
// Log decision calculation per observability spec
logger.info(
{ userId: user.id, decision: decision.status, reason: decision.reason },
"Decision calculated",
);
// Get nutrition guidance
const nutrition = getNutritionGuidance(cycleDay);