feat: overhaul Logs page with search, container logs, statistics, and rotation

- Added 4-tab layout: Service Logs, Container Logs, Statistics & Rotation, Health History
- Service Logs: service/level/line-count selector, keyword search, auto-refresh (5s)
- Container Logs: container picker, tail lines selector, auto-refresh
- Statistics & Rotation: per-service file size, entry/error/warning counts, per-service and bulk rotate buttons
- Added logsAPI in api.js: getServiceLogs, searchLogs, exportLogs, getStatistics, rotateLogs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-21 01:38:08 -04:00
parent 1a5da3a207
commit 67ddc97795
2 changed files with 511 additions and 164 deletions
+500 -164
View File
@@ -1,164 +1,500 @@
import { useState, useEffect } from 'react';
import { Activity, Clock, FileText, AlertTriangle } from 'lucide-react';
import { monitoringAPI } from '../services/api';
function Logs() {
const [backendLog, setBackendLog] = useState('');
const [healthHistory, setHealthHistory] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [tab, setTab] = useState('logs');
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
setIsLoading(true);
try {
const [logRes, healthRes] = await Promise.all([
monitoringAPI.getBackendLogs(100),
monitoringAPI.getHealthHistory(),
]);
setBackendLog(logRes.data.log || '');
setHealthHistory(healthRes.data || []);
} catch (error) {
console.error('Failed to fetch monitoring data:', error);
} finally {
setIsLoading(false);
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
</div>
);
}
return (
<div>
<div className="mb-8">
<h1 className="text-2xl font-bold text-gray-900">System Monitoring</h1>
<p className="mt-2 text-gray-600">
View backend logs and health history
</p>
</div>
<div className="mb-4 flex gap-4">
<button
className={`px-4 py-2 rounded ${tab === 'logs' ? 'bg-primary-600 text-white' : 'bg-gray-200 text-gray-800'}`}
onClick={() => setTab('logs')}
>
<FileText className="inline-block mr-2" /> Backend Logs
</button>
<button
className={`px-4 py-2 rounded ${tab === 'health' ? 'bg-primary-600 text-white' : 'bg-gray-200 text-gray-800'}`}
onClick={() => setTab('health')}
>
<Clock className="inline-block mr-2" /> Health History
</button>
</div>
{tab === 'logs' && (
<div className="card">
<div className="flex items-center mb-4">
<FileText className="h-6 w-6 text-primary-500 mr-2" />
<h3 className="text-lg font-medium text-gray-900">Backend Logs (last 100 lines)</h3>
</div>
<div className="bg-gray-900 text-green-400 p-4 rounded-lg font-mono text-sm h-96 overflow-y-auto">
<pre>{backendLog || 'No logs available.'}</pre>
</div>
</div>
)}
{tab === 'health' && (
<div className="card">
<div className="flex items-center mb-4">
<Clock className="h-6 w-6 text-primary-500 mr-2" />
<h3 className="text-lg font-medium text-gray-900">Health History (last 100 checks)</h3>
</div>
<div className="overflow-x-auto">
<table className="min-w-full text-sm">
<thead>
<tr className="bg-gray-100">
<th className="px-2 py-1 text-left">Timestamp</th>
<th className="px-2 py-1 text-left">Network</th>
<th className="px-2 py-1 text-left">WireGuard</th>
<th className="px-2 py-1 text-left">Email</th>
<th className="px-2 py-1 text-left">Calendar</th>
<th className="px-2 py-1 text-left">Files</th>
<th className="px-2 py-1 text-left">Routing</th>
<th className="px-2 py-1 text-left">Vault</th>
<th className="px-2 py-1 text-left">Alerts</th>
</tr>
</thead>
<tbody>
{healthHistory.map((h, i) => (
<tr key={i} className={h.alerts && h.alerts.length > 0 ? 'bg-red-100' : ''}>
<td className="px-2 py-1 font-mono">{h.timestamp}</td>
<td className="px-2 py-1">
{h.network?.status === 'online' || h.network?.running === true ?
<span className="text-green-600">OK</span> :
<span className="text-red-600 font-bold">Down</span>
}
</td>
<td className="px-2 py-1">
{h.wireguard?.status === 'online' || h.wireguard?.running === true ?
<span className="text-green-600">OK</span> :
<span className="text-red-600 font-bold">Down</span>
}
</td>
<td className="px-2 py-1">
{h.email?.status === 'online' || h.email?.running === true ?
<span className="text-green-600">OK</span> :
<span className="text-red-600 font-bold">Down</span>
}
</td>
<td className="px-2 py-1">
{h.calendar?.status === 'online' || h.calendar?.running === true ?
<span className="text-green-600">OK</span> :
<span className="text-red-600 font-bold">Down</span>
}
</td>
<td className="px-2 py-1">
{h.files?.status === 'online' || h.files?.running === true ?
<span className="text-green-600">OK</span> :
<span className="text-red-600 font-bold">Down</span>
}
</td>
<td className="px-2 py-1">
{h.routing?.status === 'online' || h.routing?.running === true ?
<span className="text-green-600">OK</span> :
<span className="text-red-600 font-bold">Down</span>
}
</td>
<td className="px-2 py-1">
{h.vault?.status === 'online' || h.vault?.running === true ?
<span className="text-green-600">OK</span> :
<span className="text-red-600 font-bold">Down</span>
}
</td>
<td className="px-2 py-1">
{h.alerts && h.alerts.length > 0 ? (
<div className="flex flex-col gap-1">
{h.alerts.map((a, j) => (
<span key={j} className="text-red-700 font-semibold flex items-center"><AlertTriangle className="inline-block h-4 w-4 mr-1 text-red-500" />{a}</span>
))}
</div>
) : (
<span className="text-green-600">None</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}
export default Logs;
import { useState, useEffect, useRef, useCallback } from 'react';
import {
Activity, Clock, FileText, AlertTriangle, Search, RefreshCw,
RotateCcw, Box, BarChart2, Download, ChevronDown, ChevronUp,
Filter
} from 'lucide-react';
import { monitoringAPI, logsAPI, containerAPI } from '../services/api';
const SERVICES = ['network', 'wireguard', 'routing', 'email', 'calendar', 'files', 'vault', 'container'];
const LEVELS = ['ALL', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'];
const LEVEL_COLORS = {
DEBUG: 'text-gray-400',
INFO: 'text-blue-400',
WARNING: 'text-yellow-400',
ERROR: 'text-red-400',
CRITICAL: 'text-red-600 font-bold',
};
function LevelBadge({ level }) {
const color = LEVEL_COLORS[level?.toUpperCase()] || 'text-gray-300';
return <span className={`font-mono text-xs ${color}`}>[{level}]</span>;
}
function LogLine({ entry }) {
if (entry.raw_line) {
return <div className="font-mono text-xs text-gray-300 py-0.5">{entry.raw_line}</div>;
}
return (
<div className="font-mono text-xs py-0.5 flex gap-2">
<span className="text-gray-500 shrink-0">{entry.timestamp?.slice(0, 19)}</span>
<LevelBadge level={entry.level} />
{entry.service && <span className="text-purple-400 shrink-0">[{entry.service}]</span>}
<span className="text-gray-200 break-all">{entry.message}</span>
</div>
);
}
// ── Tab: Service Logs ───────────────────────────────────────────────────────
function ServiceLogsTab() {
const [service, setService] = useState('network');
const [level, setLevel] = useState('ALL');
const [lines, setLines] = useState(100);
const [query, setQuery] = useState('');
const [logs, setLogs] = useState([]);
const [loading, setLoading] = useState(false);
const [autoRefresh, setAutoRefresh] = useState(false);
const [searchMode, setSearchMode] = useState(false);
const intervalRef = useRef(null);
const bottomRef = useRef(null);
const fetch = useCallback(async () => {
setLoading(true);
try {
if (searchMode && query) {
const res = await logsAPI.searchLogs({
query,
services: [service],
level: level === 'ALL' ? undefined : level,
});
setLogs(res.data.results || []);
} else {
const res = await logsAPI.getServiceLogs(service, level, lines);
const raw = res.data.logs || [];
const parsed = raw.map(line => {
try { return JSON.parse(line); } catch { return { raw_line: line }; }
});
setLogs(parsed.reverse());
}
} catch (e) {
setLogs([{ raw_line: `Error: ${e.message}` }]);
} finally {
setLoading(false);
}
}, [service, level, lines, query, searchMode]);
useEffect(() => {
fetch();
}, [service, level, lines]);
useEffect(() => {
if (autoRefresh) {
intervalRef.current = setInterval(fetch, 5000);
} else {
clearInterval(intervalRef.current);
}
return () => clearInterval(intervalRef.current);
}, [autoRefresh, fetch]);
return (
<div className="space-y-4">
{/* Controls */}
<div className="flex flex-wrap gap-2 items-center">
<select
className="border rounded px-2 py-1 text-sm"
value={service}
onChange={e => setService(e.target.value)}
>
{SERVICES.map(s => <option key={s} value={s}>{s}</option>)}
</select>
<select
className="border rounded px-2 py-1 text-sm"
value={level}
onChange={e => setLevel(e.target.value)}
>
{LEVELS.map(l => <option key={l} value={l}>{l}</option>)}
</select>
<select
className="border rounded px-2 py-1 text-sm"
value={lines}
onChange={e => setLines(Number(e.target.value))}
>
{[50, 100, 200, 500].map(n => <option key={n} value={n}>{n} lines</option>)}
</select>
<div className="flex gap-1 flex-1 min-w-48">
<input
className="border rounded px-2 py-1 text-sm flex-1"
placeholder="Search…"
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') { setSearchMode(true); fetch(); } }}
/>
<button
className="btn btn-secondary text-sm px-2 py-1"
onClick={() => { setSearchMode(true); fetch(); }}
title="Search"
>
<Search className="h-4 w-4" />
</button>
{query && (
<button
className="btn btn-secondary text-sm px-2 py-1"
onClick={() => { setQuery(''); setSearchMode(false); }}
>
</button>
)}
</div>
<button
className={`btn text-sm px-2 py-1 ${autoRefresh ? 'btn-primary' : 'btn-secondary'}`}
onClick={() => setAutoRefresh(v => !v)}
title="Auto-refresh every 5s"
>
<RefreshCw className={`h-4 w-4 ${autoRefresh ? 'animate-spin' : ''}`} />
</button>
<button className="btn btn-secondary text-sm px-2 py-1" onClick={fetch} title="Refresh">
<RefreshCw className="h-4 w-4" />
</button>
</div>
{/* Log output */}
<div className="bg-gray-900 rounded-lg p-3 h-[500px] overflow-y-auto">
{loading && logs.length === 0 ? (
<div className="text-gray-400 text-sm">Loading</div>
) : logs.length === 0 ? (
<div className="text-gray-500 text-sm">No log entries found.</div>
) : (
logs.map((entry, i) => <LogLine key={i} entry={entry} />)
)}
<div ref={bottomRef} />
</div>
<div className="text-xs text-gray-500">{logs.length} entries</div>
</div>
);
}
// ── Tab: Container Logs ─────────────────────────────────────────────────────
function ContainerLogsTab() {
const [containers, setContainers] = useState([]);
const [selected, setSelected] = useState('cell-api');
const [tail, setTail] = useState(100);
const [logs, setLogs] = useState('');
const [loading, setLoading] = useState(false);
const [autoRefresh, setAutoRefresh] = useState(false);
const intervalRef = useRef(null);
useEffect(() => {
containerAPI.listContainers()
.then(res => {
const names = (res.data || []).map(c => c.name || c.Names?.[0]?.replace('/', '')).filter(Boolean);
setContainers(names);
if (names.length > 0 && !names.includes(selected)) setSelected(names[0]);
})
.catch(() => {});
}, []);
const fetch = useCallback(async () => {
setLoading(true);
try {
const res = await containerAPI.getContainerLogs(selected, tail);
setLogs(res.data.logs || '');
} catch (e) {
setLogs(`Error: ${e.message}`);
} finally {
setLoading(false);
}
}, [selected, tail]);
useEffect(() => { fetch(); }, [selected, tail]);
useEffect(() => {
if (autoRefresh) {
intervalRef.current = setInterval(fetch, 5000);
} else {
clearInterval(intervalRef.current);
}
return () => clearInterval(intervalRef.current);
}, [autoRefresh, fetch]);
return (
<div className="space-y-4">
<div className="flex flex-wrap gap-2 items-center">
<select
className="border rounded px-2 py-1 text-sm"
value={selected}
onChange={e => setSelected(e.target.value)}
>
{containers.length > 0
? containers.map(c => <option key={c} value={c}>{c}</option>)
: <option value="cell-api">cell-api</option>}
</select>
<select
className="border rounded px-2 py-1 text-sm"
value={tail}
onChange={e => setTail(Number(e.target.value))}
>
{[50, 100, 200, 500].map(n => <option key={n} value={n}>{n} lines</option>)}
</select>
<button
className={`btn text-sm px-2 py-1 ${autoRefresh ? 'btn-primary' : 'btn-secondary'}`}
onClick={() => setAutoRefresh(v => !v)}
title="Auto-refresh every 5s"
>
<RefreshCw className={`h-4 w-4 ${autoRefresh ? 'animate-spin' : ''}`} />
</button>
<button className="btn btn-secondary text-sm px-2 py-1" onClick={fetch}>
<RefreshCw className="h-4 w-4" />
</button>
</div>
<div className="bg-gray-900 text-green-400 rounded-lg p-3 h-[500px] overflow-y-auto font-mono text-xs whitespace-pre-wrap">
{loading ? 'Loading…' : logs || 'No logs.'}
</div>
</div>
);
}
// ── Tab: Statistics & Rotation ──────────────────────────────────────────────
function StatisticsTab() {
const [stats, setStats] = useState({});
const [loading, setLoading] = useState(false);
const [rotating, setRotating] = useState(null);
const fetch = async () => {
setLoading(true);
try {
const res = await logsAPI.getStatistics();
setStats(res.data || {});
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
useEffect(() => { fetch(); }, []);
const rotate = async (service) => {
setRotating(service);
try {
await logsAPI.rotateLogs(service || null);
await fetch();
} catch (e) {
console.error(e);
} finally {
setRotating(null);
}
};
const fmtSize = (bytes) => {
if (!bytes) return '0 B';
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
};
const services = Object.keys(stats);
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
<h3 className="text-lg font-medium text-gray-900">Log File Statistics</h3>
<div className="flex gap-2">
<button className="btn btn-secondary text-sm" onClick={fetch}>
<RefreshCw className="h-4 w-4 mr-1 inline" /> Refresh
</button>
<button
className="btn btn-secondary text-sm"
onClick={() => rotate(null)}
disabled={rotating === 'all'}
>
<RotateCcw className="h-4 w-4 mr-1 inline" /> Rotate All
</button>
</div>
</div>
{loading ? (
<div className="text-gray-500 text-sm">Loading</div>
) : services.length === 0 ? (
<div className="text-gray-500 text-sm">No log statistics available.</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full text-sm border rounded">
<thead>
<tr className="bg-gray-100">
<th className="px-3 py-2 text-left">Service</th>
<th className="px-3 py-2 text-right">File Size</th>
<th className="px-3 py-2 text-right">Total Entries</th>
<th className="px-3 py-2 text-right">Errors</th>
<th className="px-3 py-2 text-right">Warnings</th>
<th className="px-3 py-2 text-left">Last Entry</th>
<th className="px-3 py-2 text-center">Rotate</th>
</tr>
</thead>
<tbody>
{services.map(svc => {
const s = stats[svc];
const hasError = s?.error;
const errorCount = s?.level_counts?.ERROR || 0;
const warnCount = s?.level_counts?.WARNING || 0;
return (
<tr key={svc} className="border-t hover:bg-gray-50">
<td className="px-3 py-2 font-medium">{svc}</td>
<td className="px-3 py-2 text-right font-mono">
{hasError ? '—' : fmtSize(s.file_size)}
</td>
<td className="px-3 py-2 text-right">
{hasError ? <span className="text-red-500 text-xs">{s.error}</span> : s.total_entries}
</td>
<td className={`px-3 py-2 text-right ${errorCount > 0 ? 'text-red-600 font-bold' : ''}`}>
{hasError ? '—' : errorCount}
</td>
<td className={`px-3 py-2 text-right ${warnCount > 0 ? 'text-yellow-600' : ''}`}>
{hasError ? '—' : warnCount}
</td>
<td className="px-3 py-2 font-mono text-xs text-gray-500">
{hasError ? '—' : (s.last_entry?.slice(0, 19) || '—')}
</td>
<td className="px-3 py-2 text-center">
<button
className="btn btn-secondary text-xs px-2 py-0.5"
onClick={() => rotate(svc)}
disabled={rotating === svc}
>
<RotateCcw className={`h-3 w-3 ${rotating === svc ? 'animate-spin' : ''}`} />
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
);
}
// ── Tab: Health History ─────────────────────────────────────────────────────
function HealthHistoryTab() {
const [healthHistory, setHealthHistory] = useState([]);
const [loading, setLoading] = useState(false);
const fetch = async () => {
setLoading(true);
try {
const res = await monitoringAPI.getHealthHistory();
setHealthHistory(res.data || []);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
useEffect(() => { fetch(); }, []);
const ServiceCol = ({ data }) => {
const ok = data?.status === 'online' || data?.running === true;
return ok
? <span className="text-green-600">OK</span>
: <span className="text-red-600 font-bold">Down</span>;
};
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
<h3 className="text-lg font-medium text-gray-900">Health History (last 100 checks)</h3>
<button className="btn btn-secondary text-sm" onClick={fetch}>
<RefreshCw className="h-4 w-4 mr-1 inline" /> Refresh
</button>
</div>
{loading ? (
<div className="text-gray-500 text-sm">Loading</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full text-sm">
<thead>
<tr className="bg-gray-100">
{['Timestamp', 'Network', 'WireGuard', 'Email', 'Calendar', 'Files', 'Routing', 'Vault', 'Alerts'].map(h => (
<th key={h} className="px-2 py-1 text-left">{h}</th>
))}
</tr>
</thead>
<tbody>
{healthHistory.map((h, i) => (
<tr key={i} className={h.alerts?.length > 0 ? 'bg-red-50' : ''}>
<td className="px-2 py-1 font-mono text-xs">{h.timestamp}</td>
<td className="px-2 py-1"><ServiceCol data={h.network} /></td>
<td className="px-2 py-1"><ServiceCol data={h.wireguard} /></td>
<td className="px-2 py-1"><ServiceCol data={h.email} /></td>
<td className="px-2 py-1"><ServiceCol data={h.calendar} /></td>
<td className="px-2 py-1"><ServiceCol data={h.files} /></td>
<td className="px-2 py-1"><ServiceCol data={h.routing} /></td>
<td className="px-2 py-1"><ServiceCol data={h.vault} /></td>
<td className="px-2 py-1">
{h.alerts?.length > 0 ? (
h.alerts.map((a, j) => (
<span key={j} className="text-red-700 font-semibold flex items-center gap-1">
<AlertTriangle className="h-3 w-3 text-red-500" />{a}
</span>
))
) : (
<span className="text-green-600"></span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
// ── Main Logs Page ──────────────────────────────────────────────────────────
const TABS = [
{ id: 'service', label: 'Service Logs', icon: FileText },
{ id: 'container', label: 'Container Logs', icon: Box },
{ id: 'statistics', label: 'Statistics & Rotation', icon: BarChart2 },
{ id: 'health', label: 'Health History', icon: Activity },
];
function Logs() {
const [tab, setTab] = useState('service');
return (
<div>
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">Logs & Monitoring</h1>
<p className="mt-1 text-gray-600">Search service logs, view container output, and manage log rotation.</p>
</div>
{/* Tabs */}
<div className="mb-4 flex gap-2 border-b">
{TABS.map(({ id, label, icon: Icon }) => (
<button
key={id}
className={`px-4 py-2 text-sm font-medium flex items-center gap-1 border-b-2 transition-colors ${
tab === id
? 'border-primary-600 text-primary-700'
: 'border-transparent text-gray-600 hover:text-gray-900'
}`}
onClick={() => setTab(id)}
>
<Icon className="h-4 w-4" />
{label}
</button>
))}
</div>
<div className="card">
{tab === 'service' && <ServiceLogsTab />}
{tab === 'container' && <ContainerLogsTab />}
{tab === 'statistics' && <StatisticsTab />}
{tab === 'health' && <HealthHistoryTab />}
</div>
</div>
);
}
export default Logs;