Merge pull request #5878 from carlosalbertorg/feat/log-viewer

feat: Add a Logs viewer to the admin UI
This commit is contained in:
jc21 authored and GitHub committed 2026-09-23 20:23:26 +10:00
commit c53f52ab51
27 files changed
+1262 -12

No files matched your search

+2
View File
@@ -20,6 +20,7 @@ const Settings = lazy(() => import("src/pages/Settings"));
const Certificates = lazy(() => import("src/pages/Certificates"));
const Access = lazy(() => import("src/pages/Access"));
const AuditLog = lazy(() => import("src/pages/AuditLog"));
const Logs = lazy(() => import("src/pages/Logs"));
const Users = lazy(() => import("src/pages/Users"));
const ProxyHosts = lazy(() => import("src/pages/Nginx/ProxyHosts"));
const RedirectionHosts = lazy(() => import("src/pages/Nginx/RedirectionHosts"));
@@ -65,6 +66,7 @@ function Router() {
<Route path="/certificates" element={<Certificates />} />
<Route path="/access" element={<Access />} />
<Route path="/audit-log" element={<AuditLog />} />
<Route path="/logs" element={<Logs />} />
<Route path="/settings" element={<Settings />} />
<Route path="/users" element={<Users />} />
<Route path="/nginx/proxy" element={<ProxyHosts />} />
@@ -0,0 +1,8 @@
import * as api from "./base";
import type { LogSources } from "./models";
export async function getLogSources(): Promise<LogSources> {
return await api.get({
url: "/logs/sources",
});
}
+19
View File
@@ -0,0 +1,19 @@
import * as api from "./base";
import type { LogChannel, LogHostType, LogSourceType, LogTail } from "./models";
export interface GetLogTailParams {
type: LogSourceType;
hostType?: LogHostType;
hostId?: number;
channel?: LogChannel;
lines?: number;
level?: string;
search?: string;
}
export async function getLogTail(params: GetLogTailParams): Promise<LogTail> {
return await api.get({
url: "/logs/tail",
params: { ...params },
});
}
+2
View File
@@ -26,6 +26,8 @@ export * from "./getDeadHost";
export * from "./getDeadHosts";
export * from "./getHealth";
export * from "./getHostsReport";
export * from "./getLogSources";
export * from "./getLogTail";
export * from "./getProxyHost";
export * from "./getProxyHosts";
export * from "./getRedirectionHost";
+24
View File
@@ -44,6 +44,30 @@ export interface AuditLog {
user?: User;
}
export type LogSourceType = "system" | "letsencrypt" | "host";
export type LogHostType = "proxy" | "redirection" | "dead" | "stream";
// Which of the two files nginx writes per host - named "channel", not "stream",
// to avoid confusion with the "stream" LogHostType (TCP/UDP stream hosts).
export type LogChannel = "access" | "error";
export interface LogHostOption {
id: number;
label: string;
}
export interface LogSources {
system: { label: string };
letsencrypt: { label: string };
hosts: Record<LogHostType, LogHostOption[]>;
}
export interface LogTail {
lines: string[];
size: number;
truncated: boolean;
exists: boolean;
}
export interface AccessList {
id?: number;
createdOn?: string;
+7
View File
@@ -1,6 +1,7 @@
import {
IconBook,
IconDeviceDesktop,
IconFileText,
IconHome,
IconLock,
IconSettings,
@@ -95,6 +96,12 @@ const menuItems: MenuItem[] = [
label: "auditlogs",
permissionSection: ADMIN,
},
{
to: "/logs",
icon: IconFileText,
label: "logs",
permissionSection: ADMIN,
},
{
to: "/settings",
icon: IconSettings,
+2
View File
@@ -10,6 +10,8 @@ export * from "./useDeadHosts";
export * from "./useDnsProviders";
export * from "./useHealth";
export * from "./useHostReport";
export * from "./useLogSources";
export * from "./useLogTail";
export * from "./useProxyHost";
export * from "./useProxyHosts";
export * from "./useRedirectionHost";
+15
View File
@@ -0,0 +1,15 @@
import { useQuery } from "@tanstack/react-query";
import { getLogSources, type LogSources } from "src/api/backend";
const fetchLogSources = () => getLogSources();
const useLogSources = (options = {}) => {
return useQuery<LogSources, Error>({
queryKey: ["log-sources"],
queryFn: fetchLogSources,
staleTime: 30 * 1000,
...options,
});
};
export { fetchLogSources, useLogSources };
+25
View File
@@ -0,0 +1,25 @@
import { useQuery } from "@tanstack/react-query";
import { type GetLogTailParams, getLogTail, type LogTail } from "src/api/backend";
const POLL_INTERVAL_MS = 5000;
interface UseLogTailOptions extends GetLogTailParams {
live?: boolean;
}
// Polls for new log lines while `live` is true. React Query only runs the interval
// while the tab is focused (refetchIntervalInBackground defaults to false), so an
// idle/backgrounded browser tab never generates load.
const useLogTail = ({ live = true, ...params }: UseLogTailOptions) => {
const enabled = params.type === "host" ? Boolean(params.hostType && params.hostId && params.channel) : true;
return useQuery<LogTail, Error>({
queryKey: ["log-tail", params],
queryFn: () => getLogTail(params),
enabled,
refetchInterval: live ? POLL_INTERVAL_MS : false,
placeholderData: (previousData) => previousData,
});
};
export { useLogTail };
+45
View File
@@ -488,6 +488,51 @@
"login.title": {
"defaultMessage": "Login to your account"
},
"logs": {
"defaultMessage": "Logs"
},
"logs.channel.access": {
"defaultMessage": "Access"
},
"logs.channel.error": {
"defaultMessage": "Error"
},
"logs.download": {
"defaultMessage": "Download"
},
"logs.empty": {
"defaultMessage": "No log entries yet."
},
"logs.level": {
"defaultMessage": "Level"
},
"logs.level.all": {
"defaultMessage": "All Levels"
},
"logs.lines": {
"defaultMessage": "Lines"
},
"logs.live": {
"defaultMessage": "Live"
},
"logs.paused": {
"defaultMessage": "Paused"
},
"logs.refresh": {
"defaultMessage": "Refresh"
},
"logs.search-placeholder": {
"defaultMessage": "Search log…"
},
"logs.source": {
"defaultMessage": "Source"
},
"logs.source.system": {
"defaultMessage": "System"
},
"logs.truncated-warning": {
"defaultMessage": "Only the most recent portion of this file is shown."
},
"nginx-config.label": {
"defaultMessage": "Custom Nginx Configuration"
},
+45
View File
@@ -488,6 +488,51 @@
"login.title": {
"defaultMessage": "Logi kontole sisse"
},
"logs": {
"defaultMessage": "Logid"
},
"logs.channel.access": {
"defaultMessage": "Juurdepääs"
},
"logs.channel.error": {
"defaultMessage": "Viga"
},
"logs.download": {
"defaultMessage": "Laadi alla"
},
"logs.empty": {
"defaultMessage": "Logikirjeid pole veel."
},
"logs.level": {
"defaultMessage": "Tase"
},
"logs.level.all": {
"defaultMessage": "Kõik tasemed"
},
"logs.lines": {
"defaultMessage": "Read"
},
"logs.live": {
"defaultMessage": "Reaalajas"
},
"logs.paused": {
"defaultMessage": "Peatatud"
},
"logs.refresh": {
"defaultMessage": "Värskenda"
},
"logs.search-placeholder": {
"defaultMessage": "Otsi logist…"
},
"logs.source": {
"defaultMessage": "Allikas"
},
"logs.source.system": {
"defaultMessage": "Süsteem"
},
"logs.truncated-warning": {
"defaultMessage": "Kuvatakse ainult faili kõige uuem osa."
},
"nginx-config.label": {
"defaultMessage": "Kohandatud Nginx seadistus"
},
+76
View File
@@ -0,0 +1,76 @@
import cn from "classnames";
import { useEffect, useRef } from "react";
import { T } from "src/locale";
import styles from "./LogViewer.module.css";
const LEVEL_PATTERN = /\b(ERROR|FATAL|WARN|SUCCESS|COMPLETE|DEBUG|INFO)\b/;
const levelClassName = (line: string): string | undefined => {
const match = line.match(LEVEL_PATTERN);
if (!match) {
return undefined;
}
switch (match[1]) {
case "ERROR":
case "FATAL":
return "text-danger";
case "WARN":
return "text-warning";
case "SUCCESS":
case "COMPLETE":
return "text-success";
case "DEBUG":
return "text-secondary";
default:
return undefined;
}
};
// How close to the bottom (in pixels) the user has to be for auto-scroll to keep
// following new lines. Scrolling further up than this to read history disables it,
// so newly polled lines never yank the viewport away from what's being read.
const AUTO_SCROLL_THRESHOLD_PX = 40;
interface Props {
lines: string[];
}
export default function LogLines({ lines }: Props) {
const containerRef = useRef<HTMLPreElement>(null);
const stickToBottomRef = useRef(true);
const handleScroll = () => {
const el = containerRef.current;
if (!el) {
return;
}
const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
stickToBottomRef.current = distanceFromBottom < AUTO_SCROLL_THRESHOLD_PX;
};
// biome-ignore lint/correctness/useExhaustiveDependencies: lines is a re-scroll trigger, not read in the body
useEffect(() => {
const el = containerRef.current;
if (el && stickToBottomRef.current) {
el.scrollTop = el.scrollHeight;
}
}, [lines]);
if (!lines.length) {
return (
<div className={cn(styles.logBox, "text-secondary")}>
<T id="logs.empty" />
</div>
);
}
return (
<pre ref={containerRef} onScroll={handleScroll} className={styles.logBox}>
{lines.map((line, idx) => (
<span key={idx} className={cn(styles.logLine, levelClassName(line))}>
{line}
</span>
))}
</pre>
);
}
@@ -0,0 +1,15 @@
.logBox {
height: 65vh;
overflow-y: auto;
padding: 0.75rem 1rem;
margin: 0;
font-family: var(--tblr-font-monospace, ui-monospace, monospace);
font-size: 0.8125rem;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-all;
}
.logLine {
display: block;
}
+249
View File
@@ -0,0 +1,249 @@
import { useEffect, useMemo, useState } from "react";
import Alert from "react-bootstrap/Alert";
import type { LogChannel, LogHostType, LogSourceType } from "src/api/backend";
import { Loading } from "src/components";
import { useLogSources, useLogTail } from "src/hooks";
import { T, intl } from "src/locale";
import LogLines from "./LogLines";
const LINES_OPTIONS = [100, 200, 500, 1000];
const LEVEL_OPTIONS = ["INFO", "WARN", "ERROR", "DEBUG", "SUCCESS", "FATAL", "COMPLETE"];
const SEARCH_DEBOUNCE_MS = 300;
const HOST_TYPES: { type: LogHostType; labelId: string }[] = [
{ type: "proxy", labelId: "proxy-hosts" },
{ type: "redirection", labelId: "redirection-hosts" },
{ type: "dead", labelId: "dead-hosts" },
{ type: "stream", labelId: "streams" },
];
interface Selection {
type: LogSourceType;
hostType?: LogHostType;
hostId?: number;
}
const encodeSelection = (selection: Selection): string => {
if (selection.type === "host") {
return `host:${selection.hostType}:${selection.hostId}`;
}
return selection.type;
};
const decodeSelection = (value: string): Selection => {
if (value === "system" || value === "letsencrypt") {
return { type: value };
}
const [, hostType, hostId] = value.split(":");
return { type: "host", hostType: hostType as LogHostType, hostId: Number(hostId) };
};
const formatBytes = (bytes: number): string => {
if (bytes < 1024) {
return `${bytes} B`;
}
const units = ["KB", "MB", "GB"];
let value = bytes / 1024;
let unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex++;
}
return `${value.toFixed(1)} ${units[unitIndex]}`;
};
export default function LogViewer() {
const sourcesQuery = useLogSources();
const [selection, setSelection] = useState<Selection>({ type: "system" });
const [channel, setChannel] = useState<LogChannel>("access");
const [level, setLevel] = useState("");
const [lines, setLines] = useState(LINES_OPTIONS[1]);
const [live, setLive] = useState(true);
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
useEffect(() => {
const handle = setTimeout(() => setSearch(searchInput.trim()), SEARCH_DEBOUNCE_MS);
return () => clearTimeout(handle);
}, [searchInput]);
const tailQuery = useLogTail({
type: selection.type,
hostType: selection.hostType,
hostId: selection.hostId,
channel: selection.type === "host" ? channel : undefined,
lines,
level: selection.type === "system" && level ? level : undefined,
search: search || undefined,
live,
});
const hostGroups = useMemo(() => {
if (!sourcesQuery.data) {
return [];
}
return HOST_TYPES.map(({ type, labelId }) => ({
type,
labelId,
options: sourcesQuery.data.hosts[type] || [],
})).filter((group) => group.options.length > 0);
}, [sourcesQuery.data]);
const handleDownload = () => {
const content = (tailQuery.data?.lines || []).join("\n");
const blob = new Blob([content], { type: "text/plain" });
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${encodeSelection(selection).replace(/:/g, "-")}.log`;
a.click();
window.URL.revokeObjectURL(url);
};
return (
<div className="card mt-4">
<div className="card-status-top bg-purple" />
<div className="card-header">
<div className="row w-full g-2 align-items-center">
<div className="col-auto">
<h2 className="mt-1 mb-0">
<T id="logs" />
</h2>
</div>
{typeof tailQuery.data?.size === "number" && (
<div className="col-auto">
<span className="text-secondary small">{formatBytes(tailQuery.data.size)}</span>
</div>
)}
<div className="col-auto">
<select
className="form-select form-select-sm"
value={encodeSelection(selection)}
onChange={(e) => {
setSelection(decodeSelection(e.target.value));
setChannel("access");
}}
>
<option value="system">{intl.formatMessage({ id: "logs.source.system" })}</option>
<option value="letsencrypt">{intl.formatMessage({ id: "lets-encrypt" })}</option>
{hostGroups.map((group) => (
<optgroup key={group.type} label={intl.formatMessage({ id: group.labelId })}>
{group.options.map((option) => (
<option key={option.id} value={`host:${group.type}:${option.id}`}>
{option.label}
</option>
))}
</optgroup>
))}
</select>
</div>
{selection.type === "host" && (
<div className="col-auto">
<div className="btn-group" role="group">
<button
type="button"
className={`btn btn-sm ${channel === "access" ? "btn-primary" : "btn-outline-primary"}`}
onClick={() => setChannel("access")}
>
<T id="logs.channel.access" />
</button>
<button
type="button"
className={`btn btn-sm ${channel === "error" ? "btn-primary" : "btn-outline-primary"}`}
onClick={() => setChannel("error")}
>
<T id="logs.channel.error" />
</button>
</div>
</div>
)}
{selection.type === "system" && (
<div className="col-auto">
<select
className="form-select form-select-sm"
value={level}
onChange={(e) => setLevel(e.target.value)}
>
<option value="">{intl.formatMessage({ id: "logs.level.all" })}</option>
{LEVEL_OPTIONS.map((lvl) => (
<option key={lvl} value={lvl}>
{lvl}
</option>
))}
</select>
</div>
)}
<div className="col-auto">
<input
type="search"
className="form-control form-control-sm"
placeholder={intl.formatMessage({ id: "logs.search-placeholder" })}
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
/>
</div>
<div className="col-auto">
<select
className="form-select form-select-sm"
value={lines}
onChange={(e) => setLines(Number(e.target.value))}
>
{LINES_OPTIONS.map((n) => (
<option key={n} value={n}>
{n}
</option>
))}
</select>
</div>
<div className="col-auto ms-auto d-flex gap-2">
<button
type="button"
className={`btn btn-sm ${live ? "btn-success" : "btn-outline-secondary"}`}
onClick={() => setLive((v) => !v)}
>
<T id={live ? "logs.live" : "logs.paused"} />
</button>
<button
type="button"
className="btn btn-sm btn-outline-secondary"
onClick={() => tailQuery.refetch()}
>
<T id="logs.refresh" />
</button>
<button
type="button"
className="btn btn-sm btn-outline-secondary"
disabled={!tailQuery.data?.lines.length}
onClick={handleDownload}
>
<T id="logs.download" />
</button>
</div>
</div>
</div>
{tailQuery.isError && (
<div className="card-body">
<Alert variant="danger">{tailQuery.error?.message || "Unknown error"}</Alert>
</div>
)}
{tailQuery.data?.truncated && (
<div className="card-body pb-0">
<Alert variant="warning">
<T id="logs.truncated-warning" />
</Alert>
</div>
)}
{sourcesQuery.isLoading || (tailQuery.isLoading && !tailQuery.data) ? (
<div className="card-body">
<Loading noLogo />
</div>
) : (
<LogLines lines={tailQuery.data?.lines || []} />
)}
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { HasPermission } from "src/components";
import { ADMIN, VIEW } from "src/modules/Permissions";
import LogViewer from "./LogViewer";
const Logs = () => {
return (
<HasPermission section={ADMIN} permission={VIEW} pageLoading loadingNoLogo>
<LogViewer />
</HasPermission>
);
};
export default Logs;