From fc93db73c2f59106755a77e8f9e0e314f6bffc05 Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Thu, 8 Oct 2026 16:06:39 +0200 Subject: [PATCH] fix(logs): silence health probes, one line per request, demote per-event chatter to debug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- apps/server/src/request-logging.test.ts | 78 +++++++++++++++++++++++ apps/server/src/routes/hikvision-alarm.ts | 8 ++- apps/server/src/routes/setup.ts | 2 +- apps/server/src/server.ts | 23 ++++++- apps/vision/tests/test_app.py | 17 +++++ apps/vision/vision_service/app.py | 18 ++++++ packages/devices/src/drivers/camera.ts | 7 +- packages/devices/src/drivers/common.ts | 12 ++-- wiki/concepts/app-logs.md | 19 ++++++ wiki/log.md | 8 +++ 10 files changed, 179 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/request-logging.test.ts diff --git a/apps/server/src/request-logging.test.ts b/apps/server/src/request-logging.test.ts new file mode 100644 index 0000000..76da10f --- /dev/null +++ b/apps/server/src/request-logging.test.ts @@ -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[] = []; +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(); + } + }); +}); diff --git a/apps/server/src/routes/hikvision-alarm.ts b/apps/server/src/routes/hikvision-alarm.ts index 04aa29d..ebcf299 100644 --- a/apps/server/src/routes/hikvision-alarm.ts +++ b/apps/server/src/routes/hikvision-alarm.ts @@ -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). diff --git a/apps/server/src/routes/setup.ts b/apps/server/src/routes/setup.ts index 988e3fc..2ce6e7c 100644 --- a/apps/server/src/routes/setup.ts +++ b/apps/server/src/routes/setup.ts @@ -244,7 +244,7 @@ export async function setupRoutes( eventLog?: EventLog | null, ): Promise { 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. diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9da5c72..9a23e74 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -82,6 +82,25 @@ export async function buildServer(opts: BuildOptions = {}): Promise ({ 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 ({ 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); diff --git a/apps/vision/tests/test_app.py b/apps/vision/tests/test_app.py index 60b18e3..6cc69df 100644 --- a/apps/vision/tests/test_app.py +++ b/apps/vision/tests/test_app.py @@ -49,3 +49,20 @@ def test_analyze_rejects_empty_body() -> None: headers={"content-type": "application/octet-stream"}, ) assert res.status_code == 400 + + +def test_health_access_log_lines_are_dropped() -> None: + import logging + + from vision_service.app import DropHealthAccessLog + + flt = DropHealthAccessLog() + access = logging.getLogger("uvicorn.access") + # uvicorn's access record: '%s - "%s %s HTTP/%s" %d' with (client, method, path, version, status) + fmt = '%s - "%s %s HTTP/%s" %d' + health = access.makeRecord("uvicorn.access", logging.INFO, __file__, 0, fmt, ("127.0.0.1:1", "GET", "/health", "1.1", 200), None) + analyze = access.makeRecord("uvicorn.access", logging.INFO, __file__, 0, fmt, ("127.0.0.1:1", "POST", "/analyze", "1.1", 200), None) + assert flt.filter(health) is False + assert flt.filter(analyze) is True + # The filter is installed on the live logger at import. + assert any(isinstance(f, DropHealthAccessLog) for f in access.filters) diff --git a/apps/vision/vision_service/app.py b/apps/vision/vision_service/app.py index f4e5fbc..6aec45d 100644 --- a/apps/vision/vision_service/app.py +++ b/apps/vision/vision_service/app.py @@ -8,6 +8,7 @@ advisory, never the sole authority. See wiki/entities/opencv-anpr-service.md. from __future__ import annotations +import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager @@ -34,6 +35,23 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: app = FastAPI(title="parking-vision", version="0.0.0", lifespan=lifespan) +class DropHealthAccessLog(logging.Filter): + """Drop uvicorn access-log lines for GET /health. + + The probe is hit every 30 s by Docker's HEALTHCHECK and every 8 s by the booth + server's footer chip; on a quiet booth those lines were ~90 % of this container's + output (park-2, 2026-10-08). /analyze and everything else still log. + """ + + def filter(self, record: logging.LogRecord) -> bool: + return "/health" not in record.getMessage() + + +# uvicorn applies its logging config before importing the app, so a filter added here +# survives; dictConfig replaces handlers, not a logger's filters. +logging.getLogger("uvicorn.access").addFilter(DropHealthAccessLog()) + + # Typed accessors over the untyped `app.state` (so mypy --strict sees the real types). def _recognizer(request: Request) -> Recognizer: rec: Recognizer = request.app.state.recognizer diff --git a/packages/devices/src/drivers/camera.ts b/packages/devices/src/drivers/camera.ts index e7affa2..860bff5 100644 --- a/packages/devices/src/drivers/camera.ts +++ b/packages/devices/src/drivers/camera.ts @@ -143,10 +143,9 @@ class HttpCamera implements CameraDevice { `${this.driverId} snapshot failed (${ctx.direction}): HTTP ${res.status}${busy}`, ); } - stubLog( - this.driverId, - `captureSnapshot ${ctx.direction} (${res.body.length} bytes)`, - ); + // Per-snapshot chatter → debug (a busy lane logs one every few seconds); the retry + // and failure lines above stay at info/throw. + stubLog(this.driverId, `captureSnapshot ${ctx.direction} (${res.body.length} bytes)`, "debug"); return { bytes: res.body, contentType: res.contentType || "image/jpeg", diff --git a/packages/devices/src/drivers/common.ts b/packages/devices/src/drivers/common.ts index b65ae0e..ca2ab8c 100644 --- a/packages/devices/src/drivers/common.ts +++ b/packages/devices/src/drivers/common.ts @@ -32,7 +32,8 @@ export const passwordField: ConfigField = { * Sink for stub/diagnostic device messages. Defaults to a no-op so the package * has no host/runtime dependency; the server sets this to its Fastify logger. */ -export type DeviceLogSink = (line: string) => void; +export type DeviceLogLevel = "debug" | "info" | "warn"; +export type DeviceLogSink = (line: string, level: DeviceLogLevel) => void; let sink: DeviceLogSink = () => {}; @@ -40,7 +41,10 @@ export function setDeviceLogSink(fn: DeviceLogSink): void { sink = fn; } -/** Stubs log instead of performing real I/O. Replaced with real protocols later. */ -export function stubLog(driverId: string, msg: string): void { - sink(`[device:${driverId}] ${msg}`); +/** Device-side diagnostics (the sink is the server's logger). `info` for things an + * operator reading `docker logs` should see (a config write, a retry, a clock set); + * `debug` for per-event chatter (every snapshot's byte count) that only matters under + * LOG_LEVEL=debug. */ +export function stubLog(driverId: string, msg: string, level: DeviceLogLevel = "info"): void { + sink(`[device:${driverId}] ${msg}`, level); } diff --git a/wiki/concepts/app-logs.md b/wiki/concepts/app-logs.md index 009f36f..cb0f90f 100644 --- a/wiki/concepts/app-logs.md +++ b/wiki/concepts/app-logs.md @@ -101,6 +101,25 @@ now refuses to run if any table is uncategorized). See [[local-dev-workflow]]. under diagnosis runs `LOG_LEVEL=debug` with no code change; warn+ persistence is unaffected (it filters independently in the tee). +### Noise cut (2026-10-08) + +Measured on park-2 minutes after a redeploy: 128 server lines / 15 min, of which 60 were the +Docker HEALTHCHECK's `/health` every 30 s logged as "incoming request" + "request completed"; +160 vision lines, of which 143 were uvicorn access lines for `GET /health` (Docker's probe plus +the booth server's footer-chip poll every 8 s, `DEVICE_POLL_MS`). Levels were never the problem +— all of it was `info`. Changes: + +- **`/health` is silent** (`logLevel: "silent"` on the route); vision drops `/health` access + lines with a `logging.Filter` on `uvicorn.access` (`DropHealthAccessLog`, app.py). +- **One line per request**: `disableRequestLogging` + an `onResponse` hook → + `GET /api/x → 200 12ms`. ⚠ That flag also stops Fastify's default error handler from logging + handler errors (fastify/lib/error-handler.js), so an `onError` hook logs 5xx with the stack. +- **Chatter → debug**: the hik-alarm `HIT` line (ACCEPTED/REJECTED carry everything) and the + per-snapshot `captureSnapshot … (N bytes)` line; `stubLog` gained a level argument (device + diagnostics default `info`, per-event chatter passes `"debug"`). `LOG_LEVEL=debug` restores all. + +Expected on a quiet booth: a handful of lines per hour instead of ~500. + ## The booth viewer A **Logs screen** under Setup (`/setup/logs`, gated by `log:read`, sq+en) — filter by diff --git a/wiki/log.md b/wiki/log.md index 95473e0..107f58a 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -3433,3 +3433,11 @@ a guessed 37810 frame got nothing; a parallel TCP-9100 sweep found two office pr search. Memo filed as [[device-discovery-roadmap]] (method, per-device table, rules, order: cameras → printers → relay → Dahua → DT-008 set-IP); open question #19; [[device-discovery]] and [[index]] updated. + +## [2026-10-08] query | Container log noise on a quiet booth + +park-2 right after redeploy: 128 server + 160 vision lines in 15 min, ~90 % health probes +(Docker HEALTHCHECK every 30 s; the footer chip polling vision every 8 s) logged at info. Fixed in +code, not by level: `/health` silent on both services, one request line instead of two (with an +`onError` hook so 5xx keep logging under `disableRequestLogging`), hik-alarm HIT and per-snapshot +byte lines demoted to debug via a level on `stubLog`. Pages: [[app-logs]] §Noise cut.