472 lines
19 KiB
JavaScript
472 lines
19 KiB
JavaScript
import { iconSvg } from "../icons/icons.js";
|
||
const glyph = (name) => iconSvg(name, { size: 16 });
|
||
export const logLevels = ["DEBUG", "INFO", "WARN", "ERROR"];
|
||
export function parseLogText(text) {
|
||
return text
|
||
.split(/\r?\n/)
|
||
.filter((s) => s.trim())
|
||
.map((line, i) => {
|
||
try {
|
||
const data = JSON.parse(line);
|
||
if (data && typeof data === "object" && !Array.isArray(data)) {
|
||
const raw = String(
|
||
data.level || data.severity || "INFO",
|
||
).toUpperCase(),
|
||
level =
|
||
raw === "WARNING"
|
||
? "WARN"
|
||
: logLevels.includes(raw)
|
||
? raw
|
||
: "INFO";
|
||
return {
|
||
id: i + 1,
|
||
time: String(data.timestamp || data.time || ""),
|
||
level,
|
||
source: String(data.source || data.service || "file"),
|
||
message: String(data.message || data.msg || line),
|
||
fields: data,
|
||
raw: line,
|
||
};
|
||
}
|
||
} catch {}
|
||
const match = line.match(
|
||
/^(\S+)\s+(DEBUG|INFO|WARN|WARNING|ERROR)\s+(\S+)\s+(.*)$/i,
|
||
);
|
||
return {
|
||
id: i + 1,
|
||
time: match?.[1] || "",
|
||
level: match
|
||
? match[2].toUpperCase() === "WARNING"
|
||
? "WARN"
|
||
: match[2].toUpperCase()
|
||
: "INFO",
|
||
source: match?.[3] || "file",
|
||
message: match?.[4] || line,
|
||
fields: { line: i + 1 },
|
||
raw: line,
|
||
};
|
||
});
|
||
}
|
||
function demoRecord(id) {
|
||
const level =
|
||
id % 19 === 0
|
||
? "ERROR"
|
||
: id % 11 === 0
|
||
? "WARN"
|
||
: id % 5 === 0
|
||
? "DEBUG"
|
||
: "INFO",
|
||
source = ["gateway", "identity", "worker"][id % 3];
|
||
return {
|
||
id,
|
||
time: new Date(
|
||
Date.UTC(2026, 11, 1, 12, 8, Math.floor(id / 3)),
|
||
).toISOString(),
|
||
level,
|
||
source,
|
||
message:
|
||
level === "ERROR"
|
||
? "Upstream timeout: retry scheduled"
|
||
: level === "WARN"
|
||
? "Rate limit approached for tenant demo"
|
||
: level === "DEBUG"
|
||
? "Connection pool reused"
|
||
: source === "identity"
|
||
? "Session verified successfully"
|
||
: source === "worker"
|
||
? "Background job completed"
|
||
: "HTTP request completed",
|
||
fields: {
|
||
request_id: `demo-${String(id).padStart(5, "0")}`,
|
||
duration_ms: 12 + (id % 47),
|
||
status: level === "ERROR" ? 504 : 200,
|
||
},
|
||
raw: null,
|
||
};
|
||
}
|
||
export function logsScreen({ t, heading }) {
|
||
return `${heading(t("Журнал событий", "Log reader"), t("Поиск, фильтрация и чтение потока без потери контекста.", "Search, filter and inspect a stream without losing context."))}
|
||
<section id="log-workspace" class="log-workspace" aria-label="${t("Просмотр логов", "Log viewer")}">
|
||
<div class="workspace-toolbar"><div class="workspace-context"><span class="status-badge status-badge--success" data-log-state>${glyph("check")} ${t("Демопоток", "Demo stream")}</span><span class="workspace-meta" data-log-file>anidev / production.log</span></div><div class="workspace-actions"><button type="button" data-log="pause">${t("Пауза", "Pause")}</button><label class="file-button log-open">${glyph("folder")} ${t("Открыть файл", "Open file")}<input type="file" data-log-input accept=".log,.txt,.jsonl,.json,text/plain,application/json"></label><button type="button" data-log="demo" hidden>${t("Демопоток", "Demo stream")}</button><button type="button" data-log="download">${glyph("download")}<span>${t("Экспорт", "Export")}</span></button><button type="button" data-log="clear">${glyph("trash")}<span>${t("Очистить", "Clear")}</span></button></div></div>
|
||
<form class="log-filters" role="search"><label class="log-search">${t("Поиск в журнале", "Search logs")}<input type="search" data-log-query placeholder="${t("Текст, request_id или сервис", "Text, request_id or service")}" autocomplete="off"></label><label>${t("Уровень", "Level")}<select data-log-level><option value="">${t("Все уровни", "All levels")}</option>${logLevels.map((level) => `<option>${level}</option>`).join("")}</select></label><label>${t("Сервис", "Service")}<select data-log-source><option value="">${t("Все сервисы", "All services")}</option></select></label><button type="button" data-log="reset" class="log-reset">${t("Сбросить", "Reset")}</button></form>
|
||
<div class="log-layout"><div class="log-main"><div class="log-column-labels" aria-hidden="true"><span>#</span><span>${t("Время UTC", "Time UTC")}</span><span>${t("Уровень", "Level")}</span><span>${t("Сервис", "Service")}</span><span>${t("Сообщение", "Message")}</span></div><div class="log-viewport" tabindex="0" aria-label="${t("Строки журнала. Стрелки перемещают фокус; Enter открывает событие.", "Log lines. Arrow keys move focus; Enter opens an event.")}"><ol class="log-lines"></ol><div class="log-empty" hidden><h2>${t("Нет событий", "No events")}</h2><p>${t("Измените фильтры или откройте файл журнала.", "Change filters or open a log file.")}</p></div></div></div><aside class="log-details" id="log-details" hidden aria-label="${t("Детали события", "Event details")}"><div class="log-details-heading"><h2>${t("Событие", "Event")}</h2><button type="button" data-log="close-details" aria-label="${t("Закрыть детали", "Close event details")}">${glyph("close")}</button></div><p data-log-details-summary></p><pre data-log-json tabindex="0"></pre><button type="button" data-log="copy">${glyph("copy")} ${t("Копировать JSON", "Copy JSON")}</button></aside></div>
|
||
<div class="log-footer"><span data-log-count role="status" aria-live="off"></span><div class="log-paging"><button type="button" data-log="older" aria-label="${t("Предыдущие строки", "Older lines")}">${glyph("chevron-left")}</button><button type="button" data-log="newer" aria-label="${t("Следующие строки", "Newer lines")}">${glyph("chevron-right")}</button></div><button type="button" data-log="follow" aria-pressed="true">${glyph("arrow-down")}<span>${t("Следовать за потоком", "Follow stream")}</span><b data-log-unseen hidden></b></button></div>
|
||
</section><p class="workspace-note">${t("Поток демонстрационный. Поддерживаются локальные .log, .txt и JSONL до 8 МБ. Храним последние 2000 событий; в окне — до 150 строк. Ctrl F — поиск, Ctrl End — последние события.", "This is a demo stream. Open local .log, .txt and JSONL files up to 8 MB. The latest 2,000 events are retained; up to 150 lines are rendered. Ctrl F searches, Ctrl End jumps to the latest events.")}</p>`;
|
||
}
|
||
export function mountLogs(root, { t, escape: e, notify }) {
|
||
const $ = (s) => root.querySelector(s),
|
||
abort = new AbortController(),
|
||
signal = abort.signal;
|
||
let records = Array.from({ length: 96 }, (_, i) => demoRecord(i + 1)),
|
||
id = 96,
|
||
paused = false,
|
||
pending = [],
|
||
follow = true,
|
||
windowEnd = Infinity,
|
||
selected = null,
|
||
unseen = 0,
|
||
mode = "demo",
|
||
disposed = false,
|
||
rendering = false;
|
||
const viewport = $(".log-viewport"),
|
||
list = $(".log-lines");
|
||
const rowText = (r) =>
|
||
`${r.time} ${r.level} ${r.source} ${r.message} ${JSON.stringify(r.fields)}`;
|
||
function filtered() {
|
||
const query = $("[data-log-query]").value.toLowerCase(),
|
||
level = $("[data-log-level]").value,
|
||
source = $("[data-log-source]").value;
|
||
return records.filter(
|
||
(r) =>
|
||
(!level || r.level === level) &&
|
||
(!source || r.source === source) &&
|
||
(!query || rowText(r).toLowerCase().includes(query)),
|
||
);
|
||
}
|
||
function highlight(text) {
|
||
const query = $("[data-log-query]").value;
|
||
if (!query) return e(text);
|
||
let start = 0,
|
||
result = "",
|
||
at;
|
||
while (
|
||
(at = text.toLowerCase().indexOf(query.toLowerCase(), start)) !== -1
|
||
) {
|
||
result +=
|
||
e(text.slice(start, at)) +
|
||
"<mark>" +
|
||
e(text.slice(at, at + query.length)) +
|
||
"</mark>";
|
||
start = at + query.length;
|
||
}
|
||
return result + e(text.slice(start));
|
||
}
|
||
function sources() {
|
||
const select = $("[data-log-source]"),
|
||
value = select.value;
|
||
select.innerHTML =
|
||
`<option value="">${t("Все сервисы", "All services")}</option>` +
|
||
[...new Set(records.map((r) => r.source))]
|
||
.sort()
|
||
.map((source) => `<option value="${e(source)}">${e(source)}</option>`)
|
||
.join("");
|
||
select.value = value;
|
||
}
|
||
function status() {
|
||
const badge = $("[data-log-state]");
|
||
badge.classList.toggle("status-badge--success", mode === "demo" && !paused);
|
||
badge.innerHTML =
|
||
glyph(mode === "file" ? "file" : paused ? "more-horizontal" : "check") +
|
||
" " +
|
||
(mode === "file"
|
||
? t("Файл", "File")
|
||
: paused
|
||
? t("Пауза", "Paused")
|
||
: t("Демопоток", "Demo stream"));
|
||
$('[data-log="pause"]').textContent = paused
|
||
? t("Продолжить", "Resume")
|
||
: t("Пауза", "Pause");
|
||
$('[data-log="pause"]').disabled = mode === "file";
|
||
$('[data-log="demo"]').hidden = mode === "demo";
|
||
$('[data-log="follow"]').setAttribute("aria-pressed", String(follow));
|
||
$("[data-log-unseen]").hidden = unseen === 0;
|
||
$("[data-log-unseen]").textContent = String(unseen);
|
||
if (paused && pending.length)
|
||
$("[data-log-count]").textContent = t(
|
||
`На паузе · новых событий: ${pending.length}`,
|
||
`Paused · ${pending.length} new events`,
|
||
);
|
||
}
|
||
function details(record, focus = false) {
|
||
selected = record?.id ?? null;
|
||
const panel = $(".log-details");
|
||
panel.hidden = !record;
|
||
root.classList.toggle("has-log-details", Boolean(record));
|
||
if (!record) return;
|
||
$("[data-log-details-summary]").textContent =
|
||
`${record.time} · ${record.level} · ${record.source}`;
|
||
$("[data-log-json]").textContent = JSON.stringify(
|
||
{
|
||
timestamp: record.time,
|
||
level: record.level,
|
||
source: record.source,
|
||
message: record.message,
|
||
...record.fields,
|
||
},
|
||
null,
|
||
2,
|
||
);
|
||
if (focus) $('[data-log="close-details"]').focus();
|
||
}
|
||
function render() {
|
||
if (disposed) return;
|
||
const matches = filtered(),
|
||
end = Math.min(matches.length, windowEnd),
|
||
start = Math.max(0, end - 150),
|
||
visible = matches.slice(start, end);
|
||
rendering = true;
|
||
list.innerHTML = visible
|
||
.map(
|
||
(r, i) =>
|
||
`<li><button type="button" class="log-row ${selected === r.id ? "is-selected" : ""}" data-record="${r.id}" aria-controls="log-details" aria-expanded="${selected === r.id}" tabindex="${selected === r.id || (!selected && i === 0) ? 0 : -1}"><span class="log-number">${r.id}</span><time>${e(r.time.includes("T") ? r.time.split("T")[1].replace("Z", "") : r.time || "—")}</time><span class="log-level log-level--${r.level.toLowerCase()}">${r.level}</span><span class="log-source">${e(r.source)}</span><span class="log-message">${highlight(r.message)}</span></button></li>`,
|
||
)
|
||
.join("");
|
||
$(".log-empty").hidden = visible.length > 0;
|
||
$("[data-log-count]").textContent = t(
|
||
`${visible.length ? start + 1 : 0}–${end} из ${matches.length} · всего ${records.length}`,
|
||
`${visible.length ? start + 1 : 0}–${end} of ${matches.length} · ${records.length} total`,
|
||
);
|
||
$('[data-log="older"]').disabled = start === 0;
|
||
$('[data-log="newer"]').disabled = end === matches.length;
|
||
$('[data-log="download"]').disabled = matches.length === 0;
|
||
if (selected && !visible.some((r) => r.id === selected)) details(null);
|
||
status();
|
||
if (follow) viewport.scrollTop = viewport.scrollHeight;
|
||
requestAnimationFrame(() => {
|
||
rendering = false;
|
||
});
|
||
}
|
||
function filter() {
|
||
windowEnd = Infinity;
|
||
selected = null;
|
||
details(null);
|
||
render();
|
||
}
|
||
function newest() {
|
||
follow = true;
|
||
windowEnd = Infinity;
|
||
unseen = 0;
|
||
render();
|
||
}
|
||
function closeDetails() {
|
||
const old = selected;
|
||
details(null);
|
||
render();
|
||
root.querySelector(`[data-record="${old}"]`)?.focus();
|
||
}
|
||
sources();
|
||
render();
|
||
const timer = setInterval(() => {
|
||
if (disposed || mode !== "demo") return;
|
||
const record = demoRecord(++id);
|
||
if (paused) {
|
||
pending.push(record);
|
||
pending = pending.slice(-2000);
|
||
status();
|
||
return;
|
||
}
|
||
records.push(record);
|
||
records = records.slice(-2000);
|
||
if (follow) render();
|
||
else {
|
||
unseen++;
|
||
status();
|
||
}
|
||
}, 1300);
|
||
root.addEventListener(
|
||
"click",
|
||
async (event) => {
|
||
const row = event.target.closest("[data-record]");
|
||
if (row) {
|
||
follow = false;
|
||
const record = records.find((r) => r.id === Number(row.dataset.record));
|
||
details(record, true);
|
||
render();
|
||
return;
|
||
}
|
||
const action = event.target.closest("[data-log]")?.dataset.log;
|
||
if (!action) return;
|
||
if (action === "pause") {
|
||
paused = !paused;
|
||
if (!paused) {
|
||
records = [...records, ...pending].slice(-2000);
|
||
pending = [];
|
||
}
|
||
render();
|
||
}
|
||
if (action === "follow") newest();
|
||
if (action === "older") {
|
||
follow = false;
|
||
windowEnd = Math.max(150, Math.min(filtered().length, windowEnd) - 150);
|
||
render();
|
||
}
|
||
if (action === "newer") {
|
||
const count = filtered().length;
|
||
windowEnd = Math.min(count, windowEnd + 150);
|
||
if (windowEnd === count) windowEnd = Infinity;
|
||
render();
|
||
}
|
||
if (action === "clear") {
|
||
records = [];
|
||
pending = [];
|
||
unseen = 0;
|
||
selected = null;
|
||
details(null);
|
||
render();
|
||
}
|
||
if (action === "reset") {
|
||
$("[data-log-query]").value = "";
|
||
$("[data-log-level]").value = "";
|
||
$("[data-log-source]").value = "";
|
||
filter();
|
||
}
|
||
if (action === "close-details") closeDetails();
|
||
if (action === "demo") {
|
||
mode = "demo";
|
||
paused = false;
|
||
pending = [];
|
||
records = Array.from({ length: 96 }, (_, i) => demoRecord(i + 1));
|
||
id = 96;
|
||
follow = true;
|
||
windowEnd = Infinity;
|
||
unseen = 0;
|
||
$("[data-log-file]").textContent = "anidev / production.log";
|
||
sources();
|
||
details(null);
|
||
render();
|
||
}
|
||
if (action === "copy") {
|
||
try {
|
||
await navigator.clipboard.writeText($("[data-log-json]").textContent);
|
||
notify(t("JSON скопирован", "JSON copied"));
|
||
} catch {
|
||
notify(t("Копирование недоступно", "Copying is unavailable"));
|
||
}
|
||
}
|
||
if (action === "download") {
|
||
const content =
|
||
filtered()
|
||
.map(
|
||
(r) =>
|
||
r.raw ||
|
||
`${r.time} ${r.level} ${r.source} ${r.message} ${JSON.stringify(r.fields)}`,
|
||
)
|
||
.join("\n") + "\n",
|
||
url = URL.createObjectURL(
|
||
new Blob([content], { type: "text/plain;charset=utf-8" }),
|
||
),
|
||
a = document.createElement("a");
|
||
a.href = url;
|
||
a.download = "anidev-filtered.log";
|
||
a.click();
|
||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||
}
|
||
},
|
||
{ signal },
|
||
);
|
||
for (const name of ["query", "level", "source"])
|
||
$(`[data-log-${name}]`).addEventListener(
|
||
name === "query" ? "input" : "change",
|
||
filter,
|
||
{ signal },
|
||
);
|
||
$(".log-filters").addEventListener("submit", (e) => e.preventDefault(), {
|
||
signal,
|
||
});
|
||
viewport.addEventListener(
|
||
"scroll",
|
||
() => {
|
||
if (rendering) return;
|
||
if (
|
||
viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop >
|
||
32
|
||
) {
|
||
follow = false;
|
||
status();
|
||
}
|
||
},
|
||
{ signal },
|
||
);
|
||
root.addEventListener(
|
||
"keydown",
|
||
(event) => {
|
||
const formField = event.target.matches("input,select,textarea");
|
||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "f") {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
$("[data-log-query]").focus();
|
||
return;
|
||
}
|
||
if (!formField && event.ctrlKey && event.key === "End") {
|
||
event.preventDefault();
|
||
newest();
|
||
return;
|
||
}
|
||
if (event.key === "Escape" && !$(".log-details").hidden) {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
closeDetails();
|
||
return;
|
||
}
|
||
if (formField || !event.target.closest(".log-viewport")) return;
|
||
const buttons = [...root.querySelectorAll(".log-row")],
|
||
index = buttons.indexOf(document.activeElement);
|
||
let next;
|
||
if (event.key === "ArrowDown")
|
||
next = Math.min(buttons.length - 1, index + 1);
|
||
if (event.key === "ArrowUp") next = Math.max(0, index - 1);
|
||
if (event.key === "Home") next = 0;
|
||
if (event.key === "End") next = buttons.length - 1;
|
||
if (next !== undefined) {
|
||
event.preventDefault();
|
||
buttons.forEach((b) => (b.tabIndex = -1));
|
||
if (buttons[next]) {
|
||
buttons[next].tabIndex = 0;
|
||
buttons[next].focus();
|
||
}
|
||
}
|
||
},
|
||
{ signal },
|
||
);
|
||
$("[data-log-input]").addEventListener(
|
||
"change",
|
||
async (event) => {
|
||
const file = event.target.files?.[0];
|
||
if (!file) return;
|
||
if (file.size > 8 * 1024 * 1024) {
|
||
notify(
|
||
t("Максимальный размер файла — 8 МБ", "Maximum file size is 8 MB"),
|
||
);
|
||
event.target.value = "";
|
||
return;
|
||
}
|
||
try {
|
||
const parsed = parseLogText(await file.text());
|
||
if (disposed) return;
|
||
mode = "file";
|
||
paused = true;
|
||
pending = [];
|
||
records = parsed.slice(-2000);
|
||
id = records.at(-1)?.id || 0;
|
||
follow = true;
|
||
windowEnd = Infinity;
|
||
selected = null;
|
||
unseen = 0;
|
||
$("[data-log-file]").textContent = file.name;
|
||
$("[data-log-query]").value = "";
|
||
$("[data-log-level]").value = "";
|
||
$("[data-log-source]").value = "";
|
||
sources();
|
||
details(null);
|
||
render();
|
||
if (parsed.length > 2000)
|
||
notify(
|
||
t(
|
||
"Показаны последние 2000 событий файла",
|
||
"Showing the latest 2,000 file events",
|
||
),
|
||
);
|
||
} catch {
|
||
notify(t("Не удалось прочитать файл", "Could not read the file"));
|
||
}
|
||
event.target.value = "";
|
||
},
|
||
{ signal },
|
||
);
|
||
return () => {
|
||
disposed = true;
|
||
clearInterval(timer);
|
||
abort.abort();
|
||
};
|
||
}
|