Files
parking_solution/apps/web/src/LogsViewer.tsx
T
julian 51b160bfc9 feat(logs): coalesce repeated identical lines into one row (×N badge)
A line identical to the last persisted row (level+source+message+path)
within a 5-min refreshing window updates that row — context._repeat counts
the fold, _firstAt keeps the first occurrence, createdAt tracks the latest
so the storm stays at the top of the newest-first viewer. A continuous
storm stays ONE row however long it rages, so it can't evict unrelated
history via the 50k row cap or grind the appliance disk. LogsViewer badges
coalesced rows ×N (tooltip: count + first occurrence, sq/en). In-memory
last-row cache only; a pruned-under-us row falls through to a fresh insert.

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
2026-07-10 08:29:43 +02:00

177 lines
7.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { fetchLogs, type AppLogRecord, type LogLevel } from "./api.js";
import { formatRelativeDateTime } from "./lib/format.js";
// Diagnostic log viewer (app_logs) — backend warn+ and frontend errors in one place.
// Gated by log:read server-side. Filter by level / source / since; each row expands to
// the structured context + stack. Read-only — logs are an evidence/diagnostic stream,
// never edited. See wiki/concepts/app-logs.md.
const LEVELS: LogLevel[] = ["trace", "debug", "info", "warn", "error", "fatal"];
/** Terminal-theme colour per level. */
const LEVEL_COLOR: Record<LogLevel, string> = {
trace: "text-term-muted",
debug: "text-term-muted",
info: "text-term-cyan",
warn: "text-term-amber",
error: "text-term-red",
fatal: "text-term-red",
};
function LogRow({ log }: { log: AppLogRecord }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const hasDetail = (log.context && Object.keys(log.context).length > 0) || log.stack;
// Storm-coalesced row: the server folds repeated identical lines into one row and
// counts them in context._repeat (first occurrence kept in _firstAt).
const repeat = typeof log.context?._repeat === "number" ? (log.context?._repeat as number) : null;
const firstAt = typeof log.context?._firstAt === "string" ? (log.context?._firstAt as string) : null;
return (
<div className={`border-b border-term-border/50 ${log.level === "error" || log.level === "fatal" ? "bg-term-red/5" : ""}`}>
<button
type="button"
onClick={() => hasDetail && setOpen((v) => !v)}
className={`grid w-full grid-cols-[auto_4rem_5rem_1fr_auto] items-center gap-x-3 px-1 py-1 text-left text-[0.75rem] ${
hasDetail ? "hover:bg-term-panel-2" : "cursor-default"
}`}
>
<span className="text-term-muted tabular-nums">{formatRelativeDateTime(log.createdAt, t)}</span>
<span className={`font-semibold uppercase ${LEVEL_COLOR[log.level]}`}>{log.level}</span>
<span className="text-term-muted">{t(log.source === "frontend" ? "logs.frontend" : "logs.backend")}</span>
<span className="truncate text-term-text">
{repeat != null && repeat > 1 && (
<span
className="mr-1.5 rounded-term border border-term-amber/50 px-1 text-[0.625rem] font-semibold text-term-amber"
title={t("logs.repeated", {
count: repeat,
firstAt: firstAt ? formatRelativeDateTime(firstAt, t) : "—",
})}
>
×{repeat}
</span>
)}
{log.message}
</span>
<span className="text-term-muted tabular-nums">{log.httpStatus ?? ""}</span>
</button>
{open && hasDetail && (
<div className="border-t border-term-border/40 bg-term-bg px-3 py-2">
{log.path && (
<div className="mb-1 text-[0.6875rem] text-term-muted">
{t("logs.path")}: <code className="text-term-text">{log.path}</code>
</div>
)}
{log.context && Object.keys(log.context).length > 0 && (
<pre className="mb-2 overflow-x-auto rounded-term border border-term-border bg-term-panel-2 p-2 text-[0.6875rem] text-term-text">
{JSON.stringify(log.context, null, 2)}
</pre>
)}
{log.stack && (
<pre className="overflow-x-auto rounded-term border border-term-border bg-term-panel-2 p-2 text-[0.6875rem] text-term-red/90">
{log.stack}
</pre>
)}
</div>
)}
</div>
);
}
export function LogsViewer() {
const { t } = useTranslation();
const [level, setLevel] = useState("");
const [source, setSource] = useState("");
const [since, setSince] = useState("");
const [applied, setApplied] = useState<{ level?: string; source?: string; since?: string }>({});
const q = useQuery({
queryKey: ["logs", applied],
queryFn: () => fetchLogs({ ...applied, limit: 500 }),
refetchInterval: 15_000, // keep the booth view roughly live without a WS
});
const logs = q.data?.logs ?? [];
function apply() {
setApplied({
level: level || undefined,
source: source || undefined,
since: since ? new Date(`${since}T00:00:00`).toISOString() : undefined,
});
}
function clear() {
setLevel("");
setSource("");
setSince("");
setApplied({});
}
return (
<div className="">
<div className="mb-3 flex items-center justify-between">
<h1 className="text-sm font-bold uppercase tracking-widest text-term-amber">{t("logs.title")}</h1>
<button type="button" className="btn btn-ghost btn-sm" onClick={() => q.refetch()}>
{t("logs.refresh")}
</button>
</div>
<div className="card mb-3 flex flex-wrap items-end gap-3 p-3">
<div className="field">
<span className="label">{t("logs.level")}</span>
<select className="select w-32" value={level} onChange={(e) => setLevel(e.target.value)}>
<option value="">{t("logs.allLevels")}</option>
{LEVELS.map((l) => (
<option key={l} value={l}>
{l}
</option>
))}
</select>
</div>
<div className="field">
<span className="label">{t("logs.source")}</span>
<select className="select w-36" value={source} onChange={(e) => setSource(e.target.value)}>
<option value="">{t("logs.allSources")}</option>
<option value="frontend">{t("logs.frontend")}</option>
<option value="backend">{t("logs.backend")}</option>
</select>
</div>
<div className="field">
<span className="label">{t("logs.since")}</span>
<input type="date" className="input w-40" value={since} onChange={(e) => setSince(e.target.value)} />
</div>
<button type="button" className="btn btn-primary btn-sm" onClick={apply}>
{t("logs.apply")}
</button>
<button type="button" className="btn btn-ghost btn-sm" onClick={clear}>
{t("logs.clear")}
</button>
</div>
<div className="card p-2">
{q.isLoading ? (
<div className="p-3 text-[0.75rem] text-term-muted">{t("common.loading")}</div>
) : logs.length === 0 ? (
<div className="p-3 text-[0.75rem] text-term-muted">{t("logs.empty")}</div>
) : (
<>
<div className="grid grid-cols-[auto_4rem_5rem_1fr_auto] gap-x-3 border-b border-term-border px-1 pb-1 text-[0.625rem] uppercase tracking-wider text-term-muted">
<span>{t("logs.time")}</span>
<span>{t("logs.level")}</span>
<span>{t("logs.source")}</span>
<span>{t("logs.message")}</span>
<span>{t("logs.status")}</span>
</div>
{logs.map((log) => (
<LogRow key={log.id} log={log} />
))}
</>
)}
</div>
</div>
);
}