fix(logs): silence health probes, one line per request, demote per-event chatter to debug
Measured on park-2 minutes after a redeploy: 128 server lines / 15 min, 60 of them the Docker HEALTHCHECK's /health logged as "incoming request" + "request completed"; 160 vision lines, 143 of them uvicorn access lines for GET /health (Docker's probe + the booth server's footer chip polling every 8 s). Levels were never the problem — all of it was info. - server: /health route logLevel "silent"; disableRequestLogging + an onResponse hook that logs one line "METHOD url → status Nms". That flag also stops Fastify's default error handler from logging handler errors, so an onError hook logs 5xx with the stack (fastify 5.8.5 lib/error-handler.js checks the same flag). Pinned by request-logging.test.ts. - vision: a logging.Filter on uvicorn.access drops /health access lines (tested). - devices: stubLog gains a level; the per-snapshot "captureSnapshot (N bytes)" line is debug; the hik-alarm HIT line is debug (ACCEPTED/REJECTED carry everything). LOG_LEVEL=debug restores all of it. Wiki: app-logs §Noise cut.
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createTestDb } from "@parking/db/testing";
|
||||
import { buildServer } from "./server.js";
|
||||
|
||||
// Request logging shape (2026-10-08 noise cut, wiki/concepts/app-logs.md §Noise cut):
|
||||
// - /health logs NOTHING (Docker probes it every 30 s — it was half a quiet booth's log),
|
||||
// - every other request logs ONE line "METHOD url → status Nms" (not pino's two),
|
||||
// - a handler failure still logs the error with its stack, because
|
||||
// `disableRequestLogging` also silences Fastify's default error-handler logging.
|
||||
// The logger's stream is process.stdout (pinoDbStream tees warn+ into app_logs), so
|
||||
// capture stdout writes and look at the JSON lines.
|
||||
|
||||
const lines: Record<string, unknown>[] = [];
|
||||
let restore: (() => void) | null = null;
|
||||
|
||||
function captureStdout() {
|
||||
const spy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
|
||||
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString("utf8");
|
||||
for (const l of text.split("\n")) {
|
||||
if (!l.trim()) continue;
|
||||
try {
|
||||
lines.push(JSON.parse(l));
|
||||
} catch {
|
||||
/* non-JSON stdout noise — ignore */
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}) as typeof process.stdout.write);
|
||||
restore = () => spy.mockRestore();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restore?.();
|
||||
restore = null;
|
||||
lines.length = 0;
|
||||
});
|
||||
|
||||
const msgs = () => lines.map((l) => String(l.msg ?? ""));
|
||||
|
||||
describe("request logging", () => {
|
||||
it("/health is silent; other requests log exactly one line; 5xx keeps the error", async () => {
|
||||
const t = createTestDb();
|
||||
captureStdout();
|
||||
// vitest.config forces LOG_LEVEL=silent for every test; this one needs the real level.
|
||||
const prevLevel = process.env.LOG_LEVEL;
|
||||
process.env.LOG_LEVEL = "info";
|
||||
const app = await buildServer({ db: t.db });
|
||||
process.env.LOG_LEVEL = prevLevel;
|
||||
app.get("/boom", async () => {
|
||||
throw new Error("kaboom");
|
||||
});
|
||||
await app.ready();
|
||||
try {
|
||||
lines.length = 0; // drop startup lines
|
||||
|
||||
expect((await app.inject({ method: "GET", url: "/health" })).statusCode).toBe(200);
|
||||
expect(msgs().filter((m) => m.includes("/health"))).toEqual([]);
|
||||
|
||||
expect((await app.inject({ method: "GET", url: "/api/nope" })).statusCode).toBe(404);
|
||||
const notFound = msgs().filter((m) => m.includes("/api/nope"));
|
||||
expect(notFound).toHaveLength(1);
|
||||
expect(notFound[0]).toMatch(/^GET \/api\/nope → 404 \d+ms$/);
|
||||
expect(msgs().some((m) => /incoming request|request completed/.test(m))).toBe(false);
|
||||
|
||||
expect((await app.inject({ method: "GET", url: "/boom" })).statusCode).toBe(500);
|
||||
const boom = lines.filter((l) => String(l.msg).includes("/boom"));
|
||||
// one error line (with the err object) + the one-line request summary
|
||||
expect(boom.map((l) => [l.level, String(l.msg).replace(/\d+ms/, "Nms")])).toEqual([
|
||||
["error", "GET /boom failed: kaboom"],
|
||||
["info", "GET /boom → 500 Nms"],
|
||||
]);
|
||||
expect((boom[0]!.err as { message?: string })?.message).toBe("kaboom");
|
||||
} finally {
|
||||
await app.close();
|
||||
t.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -159,9 +159,11 @@ export async function hikvisionAlarmRoutes(
|
||||
const contentType = String(req.headers["content-type"] ?? "");
|
||||
const raw: Buffer = Buffer.isBuffer(req.body) ? (req.body as Buffer) : Buffer.from("");
|
||||
const summary = summarize(raw.toString("utf8"));
|
||||
// Log EVERY hit immediately (method + ip + size), before any guard — so even a probe
|
||||
// that gets rejected is visible in the dev log the instant it arrives.
|
||||
app.log.info(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
|
||||
// Log EVERY hit immediately (method + ip + size), before any guard — so under
|
||||
// LOG_LEVEL=debug even a probe that gets rejected is visible the instant it arrives.
|
||||
// debug, not info: every accepted hit is followed by the ACCEPTED line (which carries
|
||||
// all of this plus the verdict) and every rejected one by the REJECTED warn.
|
||||
app.log.debug(`[hik-alarm:${deviceId}] HIT ${method} from ${ip} (${contentType || "no-ct"} ${raw.length}B)`);
|
||||
|
||||
// Guard: must be a known hikvision device with alarm-push enabled, posting from its
|
||||
// configured host IP. Source-IP is the primary guard on the LAN (like the Dingtian).
|
||||
|
||||
@@ -244,7 +244,7 @@ export async function setupRoutes(
|
||||
eventLog?: EventLog | null,
|
||||
): Promise<void> {
|
||||
registerBuiltinDrivers();
|
||||
setDeviceLogSink((line) => app.log.info(line));
|
||||
setDeviceLogSink((line, level) => app.log[level](line));
|
||||
|
||||
// Device setup is site administration — it changes which hardware the site runs
|
||||
// and how readers bind to relays. Gated on site:update. See ../auth.ts.
|
||||
|
||||
@@ -82,6 +82,25 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
||||
formatters: { level: (label) => ({ level: label }) },
|
||||
stream: pinoDbStream(logService, process.stdout),
|
||||
},
|
||||
// ONE line per request (the onResponse hook below) instead of Fastify's default
|
||||
// "incoming request" + "request completed" pair — on a quiet booth the pair was
|
||||
// most of the log. NB: with this flag Fastify's default error handler ALSO stops
|
||||
// logging handler errors, so the onError hook below re-adds that for 5xx.
|
||||
disableRequestLogging: true,
|
||||
});
|
||||
|
||||
// Request log, one line: method, url, status, elapsed. Routes declared with
|
||||
// `logLevel: "silent"` (the /health probe) are skipped because `req.log` is theirs.
|
||||
app.addHook("onResponse", async (req, reply) => {
|
||||
req.log.info(`${req.method} ${req.url} → ${reply.statusCode} ${Math.round(reply.elapsedTime)}ms`);
|
||||
});
|
||||
// Handler failures (5xx) keep their stack in the log — disableRequestLogging would
|
||||
// otherwise swallow them (fastify/lib/error-handler.js checks the same flag).
|
||||
app.addHook("onError", async (req, _reply, err) => {
|
||||
// onError runs BEFORE the error handler sets the reply status, so the reply still
|
||||
// says 200 here; an error without its own statusCode is a 500 by definition.
|
||||
const code = (err as { statusCode?: number }).statusCode ?? 500;
|
||||
if (code >= 500) req.log.error({ err }, `${req.method} ${req.url} failed: ${err.message}`);
|
||||
});
|
||||
|
||||
// Wire the RBAC permission resolver to this DB (route guards resolve a user's
|
||||
@@ -109,7 +128,9 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
||||
// Unauthenticated liveness probe. `app` lets a client (the desktop ConnectScreen
|
||||
// test — apps/web/src/lib/backend-config.ts) tell THIS server apart from any
|
||||
// other service that happens to answer on the address the operator typed.
|
||||
app.get("/health", async () => ({ status: "ok", app: "parking-system" }));
|
||||
// `logLevel: "silent"`: Docker's HEALTHCHECK hits this every 30 s; logging each
|
||||
// probe was half of a quiet booth's output (park-2, 2026-10-08).
|
||||
app.get("/health", { logLevel: "silent" }, async () => ({ status: "ok", app: "parking-system" }));
|
||||
|
||||
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
|
||||
await authRoutes(app, db);
|
||||
|
||||
Reference in New Issue
Block a user