feat: 工具配置增强、站点拨测与日志中心多项改进
- 工具配置:新增卸载 API/UI、Go 工具链、流水线构建自动安装依赖 - 修复 ListTools VerifyTool 递归栈溢出导致获取工具配置失败 - Node.js Alpine 安装改用 unofficial-builds musl 预编译包与 index.json 解析 LTS - 站点拨测:详情页路由、告警自动恢复、并发拨测与默认可观测频率 - 日志中心:RBAC、查询构建器、ES/Loki 增强与审计 request/response 展示 - 发布配置:构建节点、流水线远程执行、Deploy RBAC 导航拆分
This commit is contained in:
1 parent
cde7bbe540
commit
7e1c8f583c
84 files changed
+7729
-1507
No files matched your search
@@ -1,6 +1,9 @@
|
||||
// EnhancedLogResults.tsx — Grafana 风格日志结果展示 // Logan.Li
|
||||
import { useState, useMemo } from 'react';
|
||||
import { ChevronDown, ChevronRight, BarChart3, Plus, Search, Copy, Check } from 'lucide-react';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { copyToClipboard } from '@/utils/clipboard';
|
||||
import { buildLogCopyText, detectLogFields, formatLogPreview, formatLogTimestamp } from './log-format';
|
||||
import type { LogEntry, ViewMode } from './types-v3';
|
||||
type ViewDensity = 'compact' | 'comfortable' | 'loose';
|
||||
|
||||
@@ -81,25 +84,11 @@ export function extractCommonLabels(entries: LogEntry[]): Record<string, string>
|
||||
return Object.keys(common).length > 0 ? common : null;
|
||||
}
|
||||
|
||||
// ===== 检测结构化字段(从消息中解析)=====
|
||||
function detectFields(raw: string): { name: string; value: string }[] {
|
||||
const fields: { name: string; value: string }[] = [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed === 'object' && parsed !== null) {
|
||||
for (const [k, v] of Object.entries(parsed)) {
|
||||
fields.push({ name: k, value: String(v) });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 非 JSON,尝试 key=value 模式
|
||||
const regex = /(\w+)=([^,\s]+)/g;
|
||||
let m;
|
||||
while ((m = regex.exec(raw)) !== null) {
|
||||
fields.push({ name: m[1], value: m[2] });
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
// 日志行 CSS:截断关闭时用横向滚动而非省略号,避免看不到后半段 // Logan.Li
|
||||
function messageLineClass(wrap: boolean, trunc: boolean): string {
|
||||
if (wrap) return 'whitespace-pre-wrap break-all';
|
||||
if (trunc) return 'truncate';
|
||||
return 'whitespace-nowrap overflow-x-auto';
|
||||
}
|
||||
|
||||
// ===== 原始日志视图(Grafana 风格)=====
|
||||
@@ -109,15 +98,25 @@ function RawLogView({
|
||||
entry: LogEntry; wrap: boolean; trunc: boolean;
|
||||
showTime: boolean; onLabelFilter?: (k: string, v: string, op: 'include' | 'exclude') => void;
|
||||
}) {
|
||||
const { toast } = useToast();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const labels = entry.labels || {};
|
||||
const detected = useMemo(() => detectFields(entry.raw || entry.message), [entry]);
|
||||
const fullText = entry.raw || entry.message || '';
|
||||
const detected = useMemo(() => detectLogFields(fullText), [fullText]);
|
||||
const displayTs = formatLogTimestamp(entry.timestamp);
|
||||
const preview = expanded ? fullText : formatLogPreview(fullText, trunc);
|
||||
|
||||
const copyRaw = () => {
|
||||
navigator.clipboard.writeText(entry.raw || entry.message).then(() => {
|
||||
setCopied(true); setTimeout(() => setCopied(false), 1500);
|
||||
});
|
||||
const copyRaw = async () => {
|
||||
const text = buildLogCopyText(entry);
|
||||
const ok = await copyToClipboard(text);
|
||||
if (ok) {
|
||||
setCopied(true);
|
||||
toast({ title: '已复制完整日志' });
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
} else {
|
||||
toast({ title: '复制失败', description: '请展开后手动选中复制', variant: 'destructive' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -135,8 +134,8 @@ function RawLogView({
|
||||
|
||||
{/* 时间戳 */}
|
||||
{showTime && (
|
||||
<span className="text-[11px] font-mono flex-shrink-0 w-[140px] mt-0.5" style={{ color: 'var(--dg-text-muted)' }}>
|
||||
{entry.timestamp}
|
||||
<span className="text-[11px] font-mono flex-shrink-0 w-[180px] mt-0.5" style={{ color: 'var(--dg-text-muted)' }} title={entry.timestamp}>
|
||||
{displayTs}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -147,24 +146,50 @@ function RawLogView({
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* 日志内容 */}
|
||||
<span className={`text-xs flex-1 min-w-0 ${wrap ? 'whitespace-pre-wrap break-all' : 'truncate'}`} style={{ color: 'var(--dg-text-secondary)' }}>
|
||||
{trunc && entry.message.length > 300 && !expanded ? entry.message.slice(0, 300) + '...' : entry.message}
|
||||
{/* 日志内容(折叠预览) */}
|
||||
<span
|
||||
className={`text-xs font-mono flex-1 min-w-0 ${messageLineClass(wrap, trunc && !expanded)}`}
|
||||
style={{ color: 'var(--dg-text-secondary)' }}
|
||||
title={!expanded && fullText.length > 120 ? fullText : undefined}
|
||||
>
|
||||
{preview}
|
||||
</span>
|
||||
|
||||
{/* 复制按钮(hover 显示)*/}
|
||||
{/* 复制按钮(hover 显示,复制完整原文) */}
|
||||
<button
|
||||
onClick={e => { e.stopPropagation(); copyRaw(); }}
|
||||
onClick={e => { e.stopPropagation(); void copyRaw(); }}
|
||||
className="flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity mt-0.5"
|
||||
style={{ color: 'var(--dg-text-muted)' }}
|
||||
title="复制完整日志"
|
||||
>
|
||||
{copied ? <Check className="h-3 w-3 dg-text-green" /> : <Copy className="h-3 w-3" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 展开详情:Log labels + Detected fields */}
|
||||
{/* 展开详情:完整日志 + labels + fields */}
|
||||
{expanded && (
|
||||
<div className="animate-fade-in" style={{ background: 'var(--dg-bg-secondary)', padding: '8px 12px 12px 36px' }}>
|
||||
{/* 完整日志正文 */}
|
||||
<div className="mb-3">
|
||||
<div className="flex items-center justify-between mb-1.5">
|
||||
<p className="text-[10px] font-medium" style={{ color: 'var(--dg-text-muted)' }}>完整日志</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={e => { e.stopPropagation(); void copyRaw(); }}
|
||||
className="text-[10px] px-2 py-0.5 rounded border"
|
||||
style={{ borderColor: 'var(--dg-border)', color: 'var(--dg-text-secondary)' }}
|
||||
>
|
||||
{copied ? '已复制' : '复制全文'}
|
||||
</button>
|
||||
</div>
|
||||
<pre
|
||||
className="text-[11px] font-mono whitespace-pre-wrap break-all p-2 rounded max-h-[320px] overflow-y-auto"
|
||||
style={{ background: 'var(--dg-bg-tertiary)', color: 'var(--dg-text-primary)', border: '1px solid var(--dg-border)' }}
|
||||
>
|
||||
{fullText}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
{/* Log labels */}
|
||||
{Object.keys(labels).length > 0 && (
|
||||
<div className="mb-3">
|
||||
@@ -181,8 +206,8 @@ function RawLogView({
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
</button>
|
||||
<span className="text-[11px] font-mono w-[160px] truncate flex-shrink-0" style={{ color: 'var(--dg-text-primary)' }}>{k}</span>
|
||||
<span className="text-[11px] font-mono flex-1 truncate" style={{ color: 'var(--dg-text-secondary)' }}>{v}</span>
|
||||
<span className="text-[11px] font-mono w-[160px] flex-shrink-0" style={{ color: 'var(--dg-text-primary)' }}>{k}</span>
|
||||
<span className="text-[11px] font-mono flex-1 break-all" style={{ color: 'var(--dg-text-secondary)' }}>{v}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -249,12 +274,12 @@ function FieldView({ entries, wrap, trunc, search }: { entries: LogEntry[]; wrap
|
||||
<tr key={i} className="hover:opacity-80 transition-colors" style={{ borderBottom: '1px solid var(--dg-border)' }}>
|
||||
{columns.map(col => {
|
||||
let val: string;
|
||||
if (col === 'timestamp') val = e.timestamp;
|
||||
else if (col === 'message') val = e.message;
|
||||
if (col === 'timestamp') val = formatLogTimestamp(e.timestamp);
|
||||
else if (col === 'message') val = e.raw || e.message;
|
||||
else val = e.labels?.[col] || '—';
|
||||
return (
|
||||
<td key={col} className={`px-2 py-1.5 max-w-[300px] ${!wrap ? 'truncate' : 'break-all'}`} style={{ color: 'var(--dg-text-secondary)' }}>
|
||||
{trunc && val.length > 100 ? val.slice(0, 100) + '...' : val}
|
||||
<td key={col} className={`px-2 py-1.5 max-w-[400px] ${wrap ? 'break-all whitespace-pre-wrap' : trunc ? 'truncate' : 'break-all'}`} style={{ color: 'var(--dg-text-secondary)' }} title={val}>
|
||||
{trunc ? formatLogPreview(val, true, 200) : val}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
@@ -281,12 +306,12 @@ function TableView({ entries, wrap, trunc }: { entries: LogEntry[]; wrap: boolea
|
||||
<tbody>
|
||||
{entries.map((e, i) => (
|
||||
<tr key={i} className="hover:opacity-80 transition-colors" style={{ borderBottom: '1px solid var(--dg-border)' }}>
|
||||
<td className="px-3 py-2 font-mono text-[11px] whitespace-nowrap" style={{ color: 'var(--dg-text-muted)' }}>{e.timestamp}</td>
|
||||
<td className="px-3 py-2 font-mono text-[11px] whitespace-nowrap" style={{ color: 'var(--dg-text-muted)' }}>{formatLogTimestamp(e.timestamp)}</td>
|
||||
<td className="px-3 py-2">
|
||||
{e.level ? <span className={`text-[10px] px-1.5 py-0.5 rounded border ${levelBadge(e.level)}`}>{e.level}</span> : '—'}
|
||||
</td>
|
||||
<td className={`px-3 py-2 ${wrap ? 'whitespace-pre-wrap break-all' : 'truncate'} max-w-[600px]`} style={{ color: 'var(--dg-text-secondary)' }}>
|
||||
{trunc && e.message.length > 200 ? e.message.slice(0, 200) + '...' : e.message}
|
||||
<td className={`px-3 py-2 ${messageLineClass(wrap, trunc)} max-w-[800px]`} style={{ color: 'var(--dg-text-secondary)' }} title={e.raw || e.message}>
|
||||
{trunc ? formatLogPreview(e.raw || e.message, true, 300) : (e.raw || e.message)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { ChevronDown, Loader2, Search } from 'lucide-react';
|
||||
import { logCenterApi } from '@/api/log/log-center';
|
||||
|
||||
interface Props {
|
||||
datasourceId?: number;
|
||||
value: string;
|
||||
onChange: (index: string) => void;
|
||||
}
|
||||
|
||||
// ES 索引选择器 — 可搜索下拉,对接数据源索引列表 // Logan.Li
|
||||
export function EsIndexPicker({ datasourceId, value, onChange }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [indices, setIndices] = useState<string[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!datasourceId) {
|
||||
setIndices([]);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
logCenterApi.listIndicesByDatasource(datasourceId)
|
||||
.then((res) => setIndices(Array.isArray(res) ? res : []))
|
||||
.catch(() => setIndices([]))
|
||||
.finally(() => setLoading(false));
|
||||
}, [datasourceId]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
if (!q) return indices.slice(0, 80);
|
||||
return indices.filter((i) => i.toLowerCase().includes(q)).slice(0, 80);
|
||||
}, [indices, search]);
|
||||
|
||||
return (
|
||||
<div className="relative flex-shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(!open)}
|
||||
className="h-10 px-2 text-xs rounded flex items-center gap-1 font-mono min-w-[150px] max-w-[220px]"
|
||||
style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }}
|
||||
title="选择或搜索 ES 索引"
|
||||
>
|
||||
<span className="truncate flex-1 text-left">{value || '选择索引'}</span>
|
||||
{loading ? <Loader2 className="h-3 w-3 animate-spin shrink-0" /> : <ChevronDown className="h-3 w-3 shrink-0" />}
|
||||
</button>
|
||||
{open && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
<div
|
||||
className="absolute left-0 top-full mt-1 z-50 w-72 rounded-lg border shadow-xl overflow-hidden"
|
||||
style={{ background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}
|
||||
>
|
||||
<div className="p-2 border-b" style={{ borderColor: 'var(--dg-border)' }}>
|
||||
<div className="flex items-center gap-1.5 px-2 h-8 rounded" style={{ background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)' }}>
|
||||
<Search className="h-3.5 w-3.5 text-[var(--dg-text-muted)]" />
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="搜索索引..."
|
||||
className="flex-1 bg-transparent text-xs outline-none font-mono"
|
||||
style={{ color: 'var(--dg-text-primary)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-h-56 overflow-y-auto p-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { onChange(''); setOpen(false); }}
|
||||
className="w-full text-left px-2 py-1.5 text-xs rounded hover:opacity-80 font-mono"
|
||||
style={{ color: 'var(--dg-text-muted)' }}
|
||||
>
|
||||
使用数据源默认
|
||||
</button>
|
||||
{filtered.map((idx) => (
|
||||
<button
|
||||
key={idx}
|
||||
type="button"
|
||||
onClick={() => { onChange(idx); setOpen(false); }}
|
||||
className="w-full text-left px-2 py-1.5 text-xs rounded hover:opacity-80 font-mono truncate"
|
||||
style={{
|
||||
color: value === idx ? 'var(--dg-blue)' : 'var(--dg-text-secondary)',
|
||||
background: value === idx ? 'var(--dg-bg-tertiary)' : 'transparent',
|
||||
}}
|
||||
>
|
||||
{idx}
|
||||
</button>
|
||||
))}
|
||||
{!loading && filtered.length === 0 && (
|
||||
<p className="text-xs px-2 py-3 text-center" style={{ color: 'var(--dg-text-muted)' }}>无匹配索引</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { LogQueryProvider } from './LogQueryContext';
|
||||
import { UnifiedQueryPanel } from './UnifiedQueryPanel';
|
||||
import { LogDatasourcePage } from './LogDatasourcePage';
|
||||
import { LogAlertsPanel } from './LogAlertsPanel';
|
||||
import LogRBAC from './LogRBAC';
|
||||
import type { LogEngine } from './types-v3';
|
||||
|
||||
const SECTION_META: Record<string, { title: string; description: string; engine?: LogEngine }> = {
|
||||
@@ -14,9 +15,10 @@ const SECTION_META: Record<string, { title: string; description: string; engine?
|
||||
es: { title: 'ES 查询', description: '对接自建 Elasticsearch · 索引日志检索', engine: 'elasticsearch' },
|
||||
datasources: { title: '日志库', description: '管理日志数据源连接(Loki / Elasticsearch)' },
|
||||
alerts: { title: '日志告警', description: '基于查询条件的日志告警策略' },
|
||||
rbac: { title: '日志权限', description: '按 ES 索引 / Loki Label 正则限制查询范围' },
|
||||
};
|
||||
|
||||
const VALID_TABS = ['loki', 'es', 'datasources', 'alerts'];
|
||||
const VALID_TABS = ['loki', 'es', 'datasources', 'alerts', 'rbac'];
|
||||
|
||||
export default function LogCenter() {
|
||||
const { section } = useParams<{ section: string }>();
|
||||
@@ -25,6 +27,8 @@ export default function LogCenter() {
|
||||
|
||||
if (!tab) return <Navigate to="/log-center/loki" replace />;
|
||||
|
||||
if (tab === 'rbac') return <LogRBAC />;
|
||||
|
||||
const meta = SECTION_META[tab];
|
||||
|
||||
return (
|
||||
|
||||
@@ -32,7 +32,7 @@ export function LogFieldSidebar({
|
||||
}: LogFieldSidebarProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
const [showDisplay, setShowDisplay] = useState(true);
|
||||
const [showIndexed, setShowIndexed] = useState(false);
|
||||
const [showIndexed, setShowIndexed] = useState((indexedFields?.length || 0) > 0);
|
||||
|
||||
const filteredFields = useMemo(() => {
|
||||
if (!search) return fields;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { FileSearch, Database, HardDrive, AlertTriangle, Shield } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ path: '/log-center/loki', label: 'Loki 查询', icon: FileSearch },
|
||||
{ path: '/log-center/es', label: 'ES 查询', icon: Database },
|
||||
{ path: '/log-center/datasources', label: '日志库', icon: HardDrive },
|
||||
{ path: '/log-center/alerts', label: '日志告警', icon: AlertTriangle },
|
||||
{ path: '/log-center/rbac', label: '日志权限', icon: Shield },
|
||||
];
|
||||
|
||||
// 日志中心二级导航 // Logan.Li
|
||||
export function LogNav() {
|
||||
return (
|
||||
<nav className="flex items-center gap-1 p-1 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] w-fit flex-wrap">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<NavLink
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={({ isActive }) => cn(
|
||||
'flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors',
|
||||
isActive
|
||||
? 'bg-[var(--dg-bg-primary)] text-[var(--dg-text-primary)] border border-[var(--dg-border)] shadow-sm'
|
||||
: 'text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]',
|
||||
)}
|
||||
>
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
{item.label}
|
||||
</NavLink>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// LogQueryToolbar.tsx — 查询工具栏(统计条 + 分页 + 操作)// Logan.Li
|
||||
import { ArrowUpDown, Bell, Download, Copy, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { ArrowUpDown, Bell, Download, Copy, ChevronLeft, ChevronRight, ChevronsDown } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface Props {
|
||||
@@ -17,6 +17,9 @@ interface Props {
|
||||
onCopy?: () => void;
|
||||
onBellClick?: () => void;
|
||||
hasAlertRule?: boolean;
|
||||
hasMore?: boolean;
|
||||
loadingMore?: boolean;
|
||||
onLoadMore?: () => void;
|
||||
}
|
||||
|
||||
const STATUS_LABEL: Record<string, { text: string; color: string }> = {
|
||||
@@ -28,7 +31,7 @@ const STATUS_LABEL: Record<string, { text: string; color: string }> = {
|
||||
export function LogQueryToolbar({
|
||||
total, queryTime, status = 'precise', perPage, onPerPageChange,
|
||||
page, totalPages, onPageChange, sortDirection, onSortToggle,
|
||||
onExport, onCopy, onBellClick, hasAlertRule,
|
||||
onExport, onCopy, onBellClick, hasAlertRule, hasMore, loadingMore, onLoadMore,
|
||||
}: Props) {
|
||||
const [jumpPage, setJumpPage] = useState('');
|
||||
const st = STATUS_LABEL[status] || STATUS_LABEL.precise;
|
||||
@@ -131,6 +134,18 @@ export function LogQueryToolbar({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasMore && onLoadMore && (
|
||||
<button
|
||||
onClick={onLoadMore}
|
||||
disabled={loadingMore}
|
||||
className="h-7 px-2.5 text-[11px] rounded border flex items-center gap-1 disabled:opacity-40"
|
||||
style={{ borderColor: 'var(--dg-border)', color: 'var(--dg-blue)', background: 'var(--dg-bg-tertiary)' }}
|
||||
>
|
||||
<ChevronsDown className={`h-3.5 w-3.5 ${loadingMore ? 'animate-bounce' : ''}`} />
|
||||
加载更多
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* 右侧操作 */}
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { Shield, Plus, Trash2, Loader2, Users, UserPlus, Check, X, ScrollText } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { toast } from 'sonner';
|
||||
import { userApi } from '@/api';
|
||||
import { logCenterApi } from '@/api/log/log-center';
|
||||
import { logRbacApi, type LogScopeRole, type UserLogScopeRole } from '@/api/log/log-rbac';
|
||||
import { useConfirm } from '@/components/ui/confirm-dialog';
|
||||
import { PageShell } from '@/components/layout/PageShell';
|
||||
import { PageEmpty } from '@/components/layout/PageEmpty';
|
||||
|
||||
import { LogRoleCreateDialog } from './log-rbac/LogRoleCreateDialog';
|
||||
import { matchSampleScopes, SAMPLE_SCOPES, scopeDisplayLabel } from './log-rbac/matchLogScope';
|
||||
import type { LogDataSource } from '@/api/log/log-center';
|
||||
import type { JsonData } from '@/types/common';
|
||||
|
||||
const ROLE_LABEL: Record<string, string> = {
|
||||
viewer: '查看者',
|
||||
analyst: '分析者',
|
||||
};
|
||||
|
||||
const ENGINE_LABEL: Record<string, string> = {
|
||||
'*': '全部',
|
||||
loki: 'Loki',
|
||||
elasticsearch: 'ES',
|
||||
};
|
||||
|
||||
const FIELD_LABEL: Record<string, string> = {
|
||||
index: '索引',
|
||||
app: 'app',
|
||||
namespace: 'namespace',
|
||||
job: 'job',
|
||||
};
|
||||
|
||||
// 日志查询范围权限 — 正则匹配 ES 索引 / Loki Label // Logan.Li
|
||||
export default function LogRBAC() {
|
||||
const [roles, setRoles] = useState<LogScopeRole[]>([]);
|
||||
const [datasources, setDatasources] = useState<LogDataSource[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [activeTab, setActiveTab] = useState('roles');
|
||||
const [previewRoleId, setPreviewRoleId] = useState<number | null>(null);
|
||||
const [users, setUsers] = useState<JsonData[]>([]);
|
||||
const [assignments, setAssignments] = useState<UserLogScopeRole[]>([]);
|
||||
const [selectedUserId, setSelectedUserId] = useState('');
|
||||
const [assignRoleId, setAssignRoleId] = useState('');
|
||||
const [assignLoading, setAssignLoading] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [newName, setNewName] = useState('');
|
||||
const [newCode, setNewCode] = useState('');
|
||||
const [newEngine, setNewEngine] = useState('*');
|
||||
const [newMatchField, setNewMatchField] = useState('app');
|
||||
const [newPattern, setNewPattern] = useState('');
|
||||
const [newRole, setNewRole] = useState('viewer');
|
||||
const [newDatasourceId, setNewDatasourceId] = useState('');
|
||||
const [newDesc, setNewDesc] = useState('');
|
||||
const [editing, setEditing] = useState<number | null>(null);
|
||||
const [editPattern, setEditPattern] = useState('');
|
||||
const [editRole, setEditRole] = useState('');
|
||||
|
||||
const _confirm = useConfirm();
|
||||
|
||||
const loadData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [rolesRes, dsRes, usersRes] = await Promise.all([
|
||||
logRbacApi.getRoles(),
|
||||
logCenterApi.listDatasources(),
|
||||
userApi.getUsers({ page_size: 500 }),
|
||||
]);
|
||||
setRoles(Array.isArray(rolesRes) ? rolesRes : (rolesRes as JsonData)?.list || []);
|
||||
setDatasources(Array.isArray(dsRes) ? dsRes : (dsRes as JsonData)?.list || []);
|
||||
setUsers(Array.isArray(usersRes) ? usersRes : (usersRes as JsonData)?.list || []);
|
||||
} catch { /* silent */ }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
|
||||
useEffect(() => { loadData(); }, []);
|
||||
|
||||
const loadAssignments = async () => {
|
||||
if (!selectedUserId) { setAssignments([]); return; }
|
||||
try {
|
||||
const res = await logRbacApi.getUserRoles(Number(selectedUserId));
|
||||
setAssignments(Array.isArray(res) ? res : (res as JsonData)?.list || []);
|
||||
} catch { setAssignments([]); }
|
||||
};
|
||||
|
||||
useEffect(() => { loadAssignments(); }, [selectedUserId]);
|
||||
|
||||
const matchCount = useMemo(() => {
|
||||
const map: Record<number, typeof SAMPLE_SCOPES> = {};
|
||||
roles.forEach((r) => {
|
||||
map[r.id] = matchSampleScopes(r.pattern, r.match_field, r.engine);
|
||||
});
|
||||
return map;
|
||||
}, [roles]);
|
||||
|
||||
const previewMatches = previewRoleId
|
||||
? (matchCount[previewRoleId] || [])
|
||||
: SAMPLE_SCOPES;
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newName.trim() || !newCode.trim() || !newPattern.trim()) {
|
||||
toast.error('请填写名称、标识与正则'); return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await logRbacApi.createRole({
|
||||
name: newName.trim(),
|
||||
code: newCode.trim(),
|
||||
engine: newEngine,
|
||||
match_field: newMatchField,
|
||||
pattern: newPattern.trim(),
|
||||
role: newRole,
|
||||
description: newDesc,
|
||||
...(newDatasourceId ? { datasource_id: Number(newDatasourceId) } : {}),
|
||||
});
|
||||
toast.success('已创建');
|
||||
setCreateOpen(false);
|
||||
setNewName(''); setNewCode(''); setNewEngine('*'); setNewMatchField('app');
|
||||
setNewPattern(''); setNewRole('viewer'); setNewDatasourceId(''); setNewDesc('');
|
||||
loadData();
|
||||
} catch (e: unknown) {
|
||||
toast.error((e as Error)?.message || '创建失败');
|
||||
} finally { setSaving(false); }
|
||||
};
|
||||
|
||||
const handleUpdate = async (id: number) => {
|
||||
if (!editPattern.trim()) { toast.error('正则不能为空'); return; }
|
||||
setSaving(true);
|
||||
try {
|
||||
await logRbacApi.updateRole(id, { pattern: editPattern, role: editRole });
|
||||
toast.success('已更新');
|
||||
setEditing(null);
|
||||
loadData();
|
||||
} catch (e: unknown) {
|
||||
toast.error((e as Error)?.message || '更新失败');
|
||||
} finally { setSaving(false); }
|
||||
};
|
||||
|
||||
const handleDelete = async (role: LogScopeRole) => {
|
||||
const ok = await _confirm({
|
||||
title: '删除权限',
|
||||
description: `确定删除「${role.name}」?将影响 ${matchCount[role.id]?.length || 0} 个示例范围`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
if (!ok) return;
|
||||
try { await logRbacApi.deleteRole(role.id); toast.success('已删除'); loadData(); }
|
||||
catch { toast.error('删除失败'); }
|
||||
};
|
||||
|
||||
const handleToggleStatus = async (role: LogScopeRole) => {
|
||||
try {
|
||||
await logRbacApi.updateRole(role.id, { status: role.status ? 0 : 1 });
|
||||
toast.success(role.status ? '已禁用' : '已启用');
|
||||
loadData();
|
||||
} catch { toast.error('操作失败'); }
|
||||
};
|
||||
|
||||
const handleAssign = async () => {
|
||||
if (!selectedUserId || !assignRoleId) { toast.error('请选择用户和权限'); return; }
|
||||
setAssignLoading(true);
|
||||
try {
|
||||
await logRbacApi.assignRole(Number(selectedUserId), {
|
||||
log_scope_role_id: Number(assignRoleId),
|
||||
});
|
||||
toast.success('已分配');
|
||||
setAssignRoleId('');
|
||||
loadAssignments();
|
||||
} catch (e: unknown) {
|
||||
toast.error((e as Error)?.message || '分配失败');
|
||||
} finally { setAssignLoading(false); }
|
||||
};
|
||||
|
||||
const handleRevoke = async (id: number) => {
|
||||
try {
|
||||
await logRbacApi.removeRole(Number(selectedUserId), id);
|
||||
toast.success('已撤销');
|
||||
loadAssignments();
|
||||
} catch { toast.error('撤销失败'); }
|
||||
};
|
||||
|
||||
const selectedUser = users.find((u) => String(u.id) === selectedUserId);
|
||||
const pageTabs = [
|
||||
{ id: 'roles', label: '权限策略', badge: roles.length || undefined },
|
||||
{ id: 'users', label: '用户授权' },
|
||||
{ id: 'preview', label: '命中预览' },
|
||||
];
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
variant="list"
|
||||
title="日志权限"
|
||||
subtitle="按 ES 索引 / Loki Label 正则限制查询范围"
|
||||
icon={<ScrollText className="h-5 w-5" />}
|
||||
loading={loading}
|
||||
tabs={pageTabs}
|
||||
activeTab={activeTab}
|
||||
onTabChange={setActiveTab}
|
||||
actions={(
|
||||
<Button className="dg-btn-primary" onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="w-4 h-4 mr-1" />新建权限
|
||||
</Button>
|
||||
)}
|
||||
contentClassName="space-y-4"
|
||||
>
|
||||
{activeTab === 'roles' && (
|
||||
roles.length === 0 ? (
|
||||
<PageEmpty
|
||||
icon={<Shield className="h-10 w-10" />}
|
||||
title="暂无日志权限策略"
|
||||
description="创建策略并分配给用户后,将按正则限制可查询的索引与 Label 范围"
|
||||
action={<Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4 mr-1" />新建权限</Button>}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{roles.map((role) => (
|
||||
<Card key={role.id} className={`dg-card ${role.status === 0 ? 'opacity-50' : ''}`}>
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-sm font-medium text-[var(--dg-text-primary)]">{role.name}</span>
|
||||
<Badge variant="outline" className="text-[10px] border-[var(--dg-border)]">
|
||||
{ROLE_LABEL[role.role] || role.role}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-[10px] border-[var(--dg-border)]">
|
||||
{ENGINE_LABEL[role.engine] || role.engine}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-[10px] border-[var(--dg-border)]">
|
||||
{FIELD_LABEL[role.match_field] || role.match_field}
|
||||
</Badge>
|
||||
{role.status === 0 && <Badge variant="outline" className="text-[10px]">已禁用</Badge>}
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] cursor-pointer border-[var(--dg-border)]"
|
||||
onClick={() => { setActiveTab('preview'); setPreviewRoleId(role.id); }}
|
||||
>
|
||||
{matchCount[role.id]?.length || 0} 个范围
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--dg-text-muted)] mt-1 font-mono truncate">
|
||||
{role.pattern}
|
||||
{role.description ? ` · ${role.description}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{editing === role.id ? (
|
||||
<>
|
||||
<Input value={editPattern} onChange={(e) => setEditPattern(e.target.value)} className="h-7 w-32 text-xs font-mono dg-input" />
|
||||
<Select value={editRole} onValueChange={setEditRole}>
|
||||
<SelectTrigger className="h-7 w-20 text-xs"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="viewer">查看者</SelectItem>
|
||||
<SelectItem value="analyst">分析者</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => handleUpdate(role.id)}><Check className="w-3.5 h-3.5" /></Button>
|
||||
<Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => setEditing(null)}><X className="w-3.5 h-3.5" /></Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => { setEditing(role.id); setEditPattern(role.pattern); setEditRole(role.role); }}>编辑</Button>
|
||||
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggleStatus(role)}>{role.status ? '禁用' : '启用'}</Button>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-red)]" onClick={() => handleDelete(role)}><Trash2 className="w-3.5 h-3.5" /></Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{activeTab === 'users' && (
|
||||
<Card className="dg-card">
|
||||
<CardContent className="p-4 space-y-4">
|
||||
<p className="text-xs text-[var(--dg-text-muted)]">
|
||||
用户未分配任何策略时不拦截(向后兼容);分配后仅允许命中策略的查询。
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3 items-end">
|
||||
<div className="space-y-1 flex-1 min-w-[200px]">
|
||||
<Label className="text-xs">用户</Label>
|
||||
<Select value={selectedUserId} onValueChange={setSelectedUserId}>
|
||||
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder="选择用户" /></SelectTrigger>
|
||||
<SelectContent className="max-h-60">
|
||||
{users.map((u) => (
|
||||
<SelectItem key={u.id as number} value={String(u.id)}>
|
||||
{(u.real_name as string) || (u.username as string)} ({u.username as string})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1 w-48">
|
||||
<Label className="text-xs">权限策略</Label>
|
||||
<Select value={assignRoleId} onValueChange={setAssignRoleId}>
|
||||
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder="选择策略" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{roles.filter((r) => r.status === 1).map((r) => (
|
||||
<SelectItem key={r.id} value={String(r.id)}>{r.name} ({ROLE_LABEL[r.role]})</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button className="h-8" onClick={handleAssign} disabled={assignLoading || !selectedUserId || !assignRoleId}>
|
||||
{assignLoading ? <Loader2 className="w-3.5 h-3.5 mr-1 animate-spin" /> : <UserPlus className="w-3.5 h-3.5 mr-1" />}
|
||||
分配
|
||||
</Button>
|
||||
</div>
|
||||
{selectedUser ? (
|
||||
assignments.length === 0 ? (
|
||||
<p className="text-xs text-[var(--dg-text-muted)]">该用户尚未分配日志权限</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{assignments.map((a) => {
|
||||
const roleInfo = a.log_scope_role || roles.find((r) => r.id === a.log_scope_role_id);
|
||||
return (
|
||||
<div key={a.id} className="flex items-center justify-between py-2 px-2.5 rounded-md bg-[var(--dg-bg-tertiary)] text-xs">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">{ROLE_LABEL[roleInfo?.role || ''] || roleInfo?.role}</Badge>
|
||||
<span className="text-[var(--dg-text-primary)]">{roleInfo?.name}</span>
|
||||
<code className="text-[var(--dg-text-muted)] truncate">{roleInfo?.pattern}</code>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6 shrink-0" onClick={() => handleRevoke(a.id)}>
|
||||
<X className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<p className="text-xs text-[var(--dg-text-muted)] flex items-center gap-1"><Users className="w-3.5 h-3.5" />选择用户后查看已分配权限</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{activeTab === 'preview' && (
|
||||
<Card className="dg-card">
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<Button variant={previewRoleId === null ? 'secondary' : 'ghost'} size="sm" onClick={() => setPreviewRoleId(null)}>
|
||||
全部 ({SAMPLE_SCOPES.length})
|
||||
</Button>
|
||||
{roles.map((r) => (
|
||||
<Button
|
||||
key={r.id}
|
||||
variant={previewRoleId === r.id ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
className={r.status === 0 ? 'opacity-40' : ''}
|
||||
onClick={() => setPreviewRoleId(r.id)}
|
||||
>
|
||||
{r.name} ({matchCount[r.id]?.length || 0})
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5 max-h-48 overflow-y-auto">
|
||||
{previewMatches.map((s) => (
|
||||
<Badge key={s.label} variant="outline" className="text-xs font-mono border-[var(--dg-border)]">
|
||||
<Shield className="w-3 h-3 mr-0.5" />
|
||||
{scopeDisplayLabel(s)}
|
||||
</Badge>
|
||||
))}
|
||||
{previewRoleId !== null && previewMatches.length === 0 && (
|
||||
<span className="text-xs text-[var(--dg-text-muted)]">无匹配 — 请调整正则</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<LogRoleCreateDialog
|
||||
open={createOpen}
|
||||
onOpenChange={setCreateOpen}
|
||||
datasources={datasources}
|
||||
saving={saving}
|
||||
name={newName}
|
||||
code={newCode}
|
||||
engine={newEngine}
|
||||
matchField={newMatchField}
|
||||
pattern={newPattern}
|
||||
role={newRole}
|
||||
datasourceId={newDatasourceId}
|
||||
description={newDesc}
|
||||
onNameChange={setNewName}
|
||||
onCodeChange={setNewCode}
|
||||
onEngineChange={setNewEngine}
|
||||
onMatchFieldChange={setNewMatchField}
|
||||
onPatternChange={setNewPattern}
|
||||
onRoleChange={setNewRole}
|
||||
onDatasourceIdChange={setNewDatasourceId}
|
||||
onDescriptionChange={setNewDesc}
|
||||
onSubmit={handleCreate}
|
||||
/>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { ChevronDown, ChevronRight, Loader2, Tags } from 'lucide-react';
|
||||
import { logCenterApi } from '@/api/log/log-center';
|
||||
import { extractLokiSelector, mergeLokiSelector } from './query-builder';
|
||||
import type { TimeRange } from './types-v3';
|
||||
|
||||
interface Props {
|
||||
datasourceId?: number;
|
||||
query: string;
|
||||
timeRange: TimeRange;
|
||||
onQueryChange: (q: string) => void;
|
||||
}
|
||||
|
||||
// Loki Label 浏览器 — 标签名 → 标签值 → 注入 LogQL 选择器 // Logan.Li
|
||||
export function LokiLabelBrowser({ datasourceId, query, timeRange, onQueryChange }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [labels, setLabels] = useState<string[]>([]);
|
||||
const [activeLabel, setActiveLabel] = useState('');
|
||||
const [values, setValues] = useState<string[]>([]);
|
||||
const [loadingLabels, setLoadingLabels] = useState(false);
|
||||
const [loadingValues, setLoadingValues] = useState(false);
|
||||
const [selected, setSelected] = useState<Record<string, string>>({});
|
||||
|
||||
const timeParams = useCallback(() => ({
|
||||
start: timeRange.start.replace(' ', 'T'),
|
||||
end: timeRange.end.replace(' ', 'T'),
|
||||
}), [timeRange]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !datasourceId) return;
|
||||
setLoadingLabels(true);
|
||||
logCenterApi.listLokiLabels(datasourceId, timeParams())
|
||||
.then((res) => setLabels(Array.isArray(res) ? res : []))
|
||||
.catch(() => setLabels([]))
|
||||
.finally(() => setLoadingLabels(false));
|
||||
}, [open, datasourceId, timeParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeLabel || !datasourceId) {
|
||||
setValues([]);
|
||||
return;
|
||||
}
|
||||
setLoadingValues(true);
|
||||
const selector = extractLokiSelector(query);
|
||||
logCenterApi.listLokiLabelValues(datasourceId, activeLabel, {
|
||||
...timeParams(),
|
||||
...(selector ? { query: selector } : {}),
|
||||
})
|
||||
.then((res) => setValues(Array.isArray(res) ? res : []))
|
||||
.catch(() => setValues([]))
|
||||
.finally(() => setLoadingValues(false));
|
||||
}, [activeLabel, datasourceId, query, timeParams]);
|
||||
|
||||
const applySelection = (label: string, value: string) => {
|
||||
const next = { ...selected, [label]: value };
|
||||
setSelected(next);
|
||||
onQueryChange(mergeLokiSelector(query, next));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border" style={{ borderColor: 'var(--dg-border)', background: 'var(--dg-bg-secondary)' }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(!open)}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-xs font-medium"
|
||||
style={{ color: 'var(--dg-text-secondary)' }}
|
||||
>
|
||||
{open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<Tags className="h-3.5 w-3.5" style={{ color: '#06b6d4' }} />
|
||||
Label 浏览器
|
||||
{Object.keys(selected).length > 0 && (
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded" style={{ background: 'var(--dg-bg-tertiary)', color: 'var(--dg-text-muted)' }}>
|
||||
已选 {Object.keys(selected).length}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="flex border-t min-h-[140px]" style={{ borderColor: 'var(--dg-border)' }}>
|
||||
<div className="w-36 border-r overflow-y-auto max-h-48" style={{ borderColor: 'var(--dg-border)' }}>
|
||||
{loadingLabels ? (
|
||||
<div className="flex justify-center py-6"><Loader2 className="h-4 w-4 animate-spin text-[var(--dg-text-muted)]" /></div>
|
||||
) : labels.map((lb) => (
|
||||
<button
|
||||
key={lb}
|
||||
type="button"
|
||||
onClick={() => setActiveLabel(lb)}
|
||||
className="w-full text-left px-2 py-1.5 text-[11px] font-mono truncate"
|
||||
style={{
|
||||
color: activeLabel === lb ? '#06b6d4' : 'var(--dg-text-secondary)',
|
||||
background: activeLabel === lb ? 'var(--dg-bg-tertiary)' : 'transparent',
|
||||
}}
|
||||
>
|
||||
{lb}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto max-h-48 p-1">
|
||||
{!activeLabel && <p className="text-[11px] px-2 py-4 text-center" style={{ color: 'var(--dg-text-muted)' }}>选择左侧标签</p>}
|
||||
{loadingValues && <div className="flex justify-center py-6"><Loader2 className="h-4 w-4 animate-spin" /></div>}
|
||||
{!loadingValues && activeLabel && values.map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
onClick={() => applySelection(activeLabel, v)}
|
||||
className="w-full text-left px-2 py-1 text-[11px] font-mono truncate rounded hover:opacity-80"
|
||||
style={{
|
||||
color: selected[activeLabel] === v ? '#22c55e' : 'var(--dg-text-primary)',
|
||||
background: selected[activeLabel] === v ? 'rgba(34,197,94,0.1)' : 'transparent',
|
||||
}}
|
||||
>
|
||||
{v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { useState, useMemo, useCallback, useRef, useEffect } from 'react';
|
||||
import { highlightSyntax } from './query-syntax';
|
||||
import {
|
||||
detectAutocompleteContext,
|
||||
filterSuggestions,
|
||||
applySuggestion,
|
||||
type AutocompleteContext,
|
||||
} from './query-autocomplete';
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
engine: 'loki' | 'elasticsearch';
|
||||
placeholder?: string;
|
||||
labelNames?: string[];
|
||||
labelValues?: string[];
|
||||
mappingFields?: string[];
|
||||
onRequestLabelValues?: (label: string) => void;
|
||||
}
|
||||
|
||||
// 语法高亮 + 自动补全查询输入框 // Logan.Li
|
||||
export function QueryAutocompleteInput({
|
||||
value,
|
||||
onChange,
|
||||
engine,
|
||||
placeholder,
|
||||
labelNames = [],
|
||||
labelValues = [],
|
||||
mappingFields = [],
|
||||
onRequestLabelValues,
|
||||
}: Props) {
|
||||
const taRef = useRef<HTMLTextAreaElement>(null);
|
||||
const preRef = useRef<HTMLPreElement>(null);
|
||||
const [ctx, setCtx] = useState<AutocompleteContext | null>(null);
|
||||
const [activeIdx, setActiveIdx] = useState(0);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const sync = useCallback(() => {
|
||||
if (preRef.current && taRef.current) {
|
||||
preRef.current.scrollLeft = taRef.current.scrollLeft;
|
||||
preRef.current.scrollTop = taRef.current.scrollTop;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const suggestions = useMemo(() => {
|
||||
if (!ctx) return [];
|
||||
return filterSuggestions(ctx, labelNames, labelValues, mappingFields);
|
||||
}, [ctx, labelNames, labelValues, mappingFields]);
|
||||
|
||||
const updateContext = useCallback(() => {
|
||||
const el = taRef.current;
|
||||
if (!el) return;
|
||||
const next = detectAutocompleteContext(value, el.selectionStart, engine);
|
||||
setCtx(next);
|
||||
setOpen(!!next);
|
||||
setActiveIdx(0);
|
||||
if (next?.kind === 'value' && next.labelName) {
|
||||
onRequestLabelValues?.(next.labelName);
|
||||
}
|
||||
}, [value, engine, onRequestLabelValues]);
|
||||
|
||||
const pickSuggestion = useCallback((s: string) => {
|
||||
if (!ctx) return;
|
||||
const { text, cursor } = applySuggestion(value, ctx, s);
|
||||
onChange(text);
|
||||
setOpen(false);
|
||||
setCtx(null);
|
||||
requestAnimationFrame(() => {
|
||||
const el = taRef.current;
|
||||
if (el) {
|
||||
el.focus();
|
||||
el.selectionStart = el.selectionEnd = cursor;
|
||||
}
|
||||
});
|
||||
}, [ctx, value, onChange]);
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (open && suggestions.length > 0) {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setActiveIdx((i) => Math.min(i + 1, suggestions.length - 1));
|
||||
return;
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setActiveIdx((i) => Math.max(i - 1, 0));
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
pickSuggestion(suggestions[activeIdx]);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (e.key === 'Tab' && !open) {
|
||||
e.preventDefault();
|
||||
const t = e.currentTarget;
|
||||
const s = t.selectionStart;
|
||||
const ed = t.selectionEnd;
|
||||
onChange(value.slice(0, s) + ' ' + value.slice(ed));
|
||||
requestAnimationFrame(() => { t.selectionStart = t.selectionEnd = s + 2; });
|
||||
}
|
||||
if (e.key === ' ' && e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
updateContext();
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
updateContext();
|
||||
}, [value, open, updateContext]);
|
||||
|
||||
const html = useMemo(() => highlightSyntax(value, engine), [value, engine]);
|
||||
|
||||
return (
|
||||
<div className="relative flex-1 min-w-[120px]">
|
||||
<div
|
||||
className="relative"
|
||||
style={{ height: '40px', background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', borderRadius: '0.25rem' }}
|
||||
>
|
||||
<textarea
|
||||
ref={taRef}
|
||||
value={value}
|
||||
onChange={(e) => { onChange(e.target.value); updateContext(); }}
|
||||
onScroll={sync}
|
||||
onKeyDown={onKeyDown}
|
||||
onClick={updateContext}
|
||||
onFocus={updateContext}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
rows={1}
|
||||
className="absolute inset-0 w-full h-full font-mono text-xs rounded resize-none outline-none overflow-auto whitespace-pre-wrap break-all px-3 py-2.5"
|
||||
style={{ background: 'transparent', color: 'transparent', caretColor: 'var(--dg-text-primary)', lineHeight: '20px', zIndex: 1 }}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
<pre
|
||||
ref={preRef}
|
||||
className="absolute inset-0 m-0 font-mono text-xs rounded pointer-events-none overflow-hidden whitespace-pre-wrap break-all px-3 py-2.5"
|
||||
style={{ background: 'transparent', lineHeight: '20px', color: 'var(--dg-text-primary)', zIndex: 2 }}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
{!value && (
|
||||
<div className="absolute inset-0 flex items-center px-3 pointer-events-none" style={{ zIndex: 3 }}>
|
||||
<span className="text-xs font-mono" style={{ color: 'var(--dg-text-muted)' }}>{placeholder}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{open && suggestions.length > 0 && (
|
||||
<div
|
||||
className="absolute left-0 right-0 top-full mt-1 z-50 max-h-40 overflow-y-auto rounded border shadow-lg"
|
||||
style={{ background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}
|
||||
>
|
||||
{suggestions.map((s, i) => (
|
||||
<button
|
||||
key={`${s}-${i}`}
|
||||
type="button"
|
||||
onMouseDown={(e) => { e.preventDefault(); pickSuggestion(s); }}
|
||||
className="w-full text-left px-3 py-1.5 text-xs font-mono truncate"
|
||||
style={{
|
||||
color: i === activeIdx ? 'var(--dg-blue)' : 'var(--dg-text-secondary)',
|
||||
background: i === activeIdx ? 'var(--dg-bg-tertiary)' : 'transparent',
|
||||
}}
|
||||
>
|
||||
{s}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useState } from 'react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
|
||||
const ALL_TEMPLATES: Record<'loki' | 'elasticsearch', { label: string; query: string }[]> = {
|
||||
loki: [
|
||||
{ label: 'Nginx 错误', query: '{job="nginx"} |= "error"' },
|
||||
{ label: 'JSON 过滤', query: '{namespace="prod"} | json | level="warn"' },
|
||||
{ label: '超时搜索', query: '{app="api"} |= "timeout"' },
|
||||
{ label: '级别统计', query: 'sum by(level) (count_over_time({job="app"}[5m]))' },
|
||||
{ label: '正则多级别', query: '{container="frontend"} |~ "ERROR|WARN|FATAL"' },
|
||||
{ label: '慢请求>1s', query: '{job="api"} | json | response_time > 1000' },
|
||||
{ label: '错误率统计', query: 'sum by(level) (count_over_time({app="cex-admin-api"} |= "error" [5m]))' },
|
||||
{ label: '追踪ID查询', query: '{app="cex-admin-api"} |= "trace_id" | json' },
|
||||
{ label: '服务聚合', query: 'sum by(service_name) (count_over_time({namespace="astralx"}[5m]))' },
|
||||
{ label: '高延迟筛选', query: '{app="cex-admin-api"} | json | response_time > 500' },
|
||||
{ label: '异常堆栈', query: '{app="cex-admin-api"} |= "Exception"' },
|
||||
{ label: '日志趋势', query: 'sum(count_over_time({app="cex-admin-api"}[1h]))' },
|
||||
{ label: '正则提取', query: '{app="cex-admin-api"} | regexp "(?P<method>[A-Za-z0-9_]+) (?P<path>[^ ]+)"' },
|
||||
{ label: '格式输出', query: '{app="cex-admin-api"} | json | line_format "{{.level}} {{.message}}"' },
|
||||
],
|
||||
elasticsearch: [
|
||||
{ label: 'API 5xx', query: 'status:500 AND path:"/api/*"' },
|
||||
{ label: '错误超时', query: '(level:error OR log.level:error) AND message:*timeout*' },
|
||||
{ label: '排除调试', query: 'host.name:server-* AND NOT level:debug' },
|
||||
{ label: '慢请求', query: 'response_time:>1000 AND method:POST' },
|
||||
{ label: '严重错误', query: '@timestamp:[now-1h TO now] AND (level:critical OR log.level:critical)' },
|
||||
{ label: '服务错误', query: 'service:nginx AND (level:(error OR fatal) OR log.level:(error OR fatal))' },
|
||||
{ label: '组合查询', query: 'app:cex-admin-api AND (level:(error OR warn) OR log.level:(error OR warn))' },
|
||||
{ label: '模糊匹配', query: 'message:*timeout* AND app:cex-admin-api' },
|
||||
{ label: '范围查询', query: 'response_time:[1000 TO *] AND method:POST' },
|
||||
{ label: '排除路径', query: 'app:cex-admin-api AND NOT path:/health' },
|
||||
{ label: '时间过滤', query: '@timestamp:[now-1h TO now] AND level:error' },
|
||||
{ label: 'IP段过滤', query: 'client_ip:172.36.* AND app:cex-admin-api' },
|
||||
{ label: '多级别筛选', query: 'app:cex-admin-api AND (level:(error OR warn OR info) OR log.level:(error OR warn OR info))' },
|
||||
{ label: '嵌套字段', query: 'labels.orgId:10001 AND app:cex-admin-api' },
|
||||
],
|
||||
};
|
||||
|
||||
// 快捷查询模板条 // Logan.Li
|
||||
export function QuickQueryBar({ engine, onSelect }: { engine: 'loki' | 'elasticsearch'; onSelect: (q: string) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const templates = ALL_TEMPLATES[engine];
|
||||
const labels: Record<'loki' | 'elasticsearch', string> = { loki: 'LogQL', elasticsearch: 'Lucene' };
|
||||
return (
|
||||
<div>
|
||||
<button onClick={() => setOpen(!open)} className="flex items-center gap-1 text-[11px] px-2 py-1 rounded transition-colors" style={{ color: 'var(--dg-blue)', background: open ? 'var(--dg-bg-tertiary)' : 'transparent' }}>
|
||||
<span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--dg-blue)' }} />
|
||||
{labels[engine]} 快捷查询模板
|
||||
<ChevronDown className="h-3 w-3" style={{ transform: open ? 'rotate(0deg)' : 'rotate(-90deg)', transition: 'transform 0.2s' }} />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="mt-1.5 p-2.5 rounded-lg border" style={{ background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}>
|
||||
<div className="grid grid-cols-3 lg:grid-cols-4 gap-1.5">
|
||||
{templates.map((t) => (
|
||||
<button key={t.label} onClick={() => { onSelect(t.query); setOpen(false); }} className="text-left px-2 py-1.5 rounded border text-[11px] transition-all hover:opacity-80" style={{ background: 'var(--dg-bg-tertiary)', borderColor: 'var(--dg-border)', color: 'var(--dg-text-secondary)' }} title={t.query}>
|
||||
<span className="font-medium block truncate" style={{ color: 'var(--dg-text-primary)' }}>{t.label}</span>
|
||||
<span className="block truncate opacity-60 font-mono mt-0.5 text-[10px]">{t.query}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { X, Save, BellRing, Loader2 } from 'lucide-react';
|
||||
import { alertApi } from '@/api';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import type { LogEngine, TimeRange } from './types-v3';
|
||||
import { ENGINE_META } from './types-v3';
|
||||
import { ENGINE_META, savedQueryStorage } from './types-v3';
|
||||
|
||||
interface SaveQueryProps {
|
||||
open: boolean;
|
||||
@@ -12,11 +12,12 @@ interface SaveQueryProps {
|
||||
engine: LogEngine;
|
||||
query: string;
|
||||
timeRange: TimeRange;
|
||||
datasourceId?: number;
|
||||
datasourceName?: string;
|
||||
onSave?: (name: string) => void;
|
||||
}
|
||||
|
||||
export function SaveQueryDialog({ open, onClose, engine, query, timeRange, datasourceName, onSave }: SaveQueryProps) {
|
||||
export function SaveQueryDialog({ open, onClose, engine, query, timeRange, datasourceId, datasourceName, onSave }: SaveQueryProps) {
|
||||
const [name, setName] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
@@ -24,9 +25,20 @@ export function SaveQueryDialog({ open, onClose, engine, query, timeRange, datas
|
||||
if (!open) return null;
|
||||
|
||||
const handleSave = () => {
|
||||
if (!name.trim()) return;
|
||||
if (!name.trim() || !datasourceId) return;
|
||||
setSaving(true);
|
||||
setTimeout(() => { setSaving(false); setSaved(true); onSave?.(name); setTimeout(() => { setSaved(false); onClose(); }, 800); }, 500);
|
||||
savedQueryStorage.add({
|
||||
name: name.trim(),
|
||||
engine,
|
||||
datasourceId,
|
||||
query,
|
||||
queryType: 'logs',
|
||||
timeRangeLabel: timeRange.label,
|
||||
});
|
||||
setSaving(false);
|
||||
setSaved(true);
|
||||
onSave?.(name.trim());
|
||||
setTimeout(() => { setSaved(false); setName(''); onClose(); }, 600);
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { X, Trash2, Play, Bookmark, Clock } from 'lucide-react';
|
||||
import type { SavedQuery } from './types-v3';
|
||||
import { savedQueryStorage } from './types-v3';
|
||||
import { ENGINE_META } from './types-v3';
|
||||
|
||||
interface Props {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (item: SavedQuery) => void;
|
||||
}
|
||||
|
||||
// 已保存查询面板(localStorage)// Logan.Li
|
||||
export function SavedQueriesPanel({ visible, onClose, onSelect }: Props) {
|
||||
const [items, setItems] = useState<SavedQuery[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) setItems(savedQueryStorage.getAll());
|
||||
}, [visible]);
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" style={{ background: 'rgba(0,0,0,0.3)' }} onClick={onClose} />
|
||||
<div
|
||||
className="fixed right-0 top-0 h-full z-50 border-l flex flex-col"
|
||||
style={{ width: '380px', background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: 'var(--dg-border)' }}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Bookmark className="h-4 w-4" style={{ color: 'var(--dg-blue)' }} />
|
||||
<span className="text-sm font-medium" style={{ color: 'var(--dg-text-primary)' }}>已保存查询</span>
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded" style={{ background: 'var(--dg-bg-tertiary)', color: 'var(--dg-text-muted)' }}>
|
||||
{items.length}
|
||||
</span>
|
||||
</div>
|
||||
<button onClick={onClose} className="h-7 w-7 flex items-center justify-center" style={{ color: 'var(--dg-text-muted)' }}>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-2">
|
||||
{items.length === 0 ? (
|
||||
<p className="text-xs text-center py-8" style={{ color: 'var(--dg-text-muted)' }}>暂无保存的查询</p>
|
||||
) : items.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="p-3 rounded-lg border group"
|
||||
style={{ background: 'var(--dg-bg-tertiary)', borderColor: 'var(--dg-border)' }}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium truncate" style={{ color: 'var(--dg-text-primary)' }}>{item.name}</p>
|
||||
<p className="text-[10px] mt-0.5" style={{ color: ENGINE_META[item.engine]?.color || 'var(--dg-text-muted)' }}>
|
||||
{ENGINE_META[item.engine]?.name} · {item.timeRangeLabel}
|
||||
</p>
|
||||
<p className="text-[11px] font-mono mt-1 truncate" style={{ color: 'var(--dg-text-secondary)' }}>{item.query}</p>
|
||||
<p className="text-[10px] mt-1 flex items-center gap-1" style={{ color: 'var(--dg-text-muted)' }}>
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(item.createdAt).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 opacity-80 group-hover:opacity-100">
|
||||
<button
|
||||
onClick={() => { onSelect(item); onClose(); }}
|
||||
className="h-7 w-7 flex items-center justify-center rounded border"
|
||||
style={{ borderColor: 'var(--dg-border)', color: '#22c55e' }}
|
||||
title="应用"
|
||||
>
|
||||
<Play className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { savedQueryStorage.remove(item.id); setItems(savedQueryStorage.getAll()); }}
|
||||
className="h-7 w-7 flex items-center justify-center rounded border"
|
||||
style={{ borderColor: 'var(--dg-border)', color: 'var(--dg-text-muted)' }}
|
||||
title="删除"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// UnifiedQueryPanel.tsx — 统一查询面板(接入真实 API)// Logan.Li
|
||||
import { useState, useMemo, useCallback, useRef, useEffect } from 'react';
|
||||
import { Play, Loader2, Clock, Save, ChevronDown, Bell } from 'lucide-react';
|
||||
import { useSearchParams, useLocation } from 'react-router-dom';
|
||||
import { Play, Loader2, Clock, Save, ChevronDown, Bell, Link2, Bookmark, Radio } from 'lucide-react';
|
||||
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import { TimeRangePicker } from './TimeRangePicker';
|
||||
import { LogFieldSidebar } from './LogFieldSidebar';
|
||||
@@ -10,9 +11,18 @@ import { StatChartPanel } from './StatChartPanel';
|
||||
import { LogClusterPanel } from './LogClusterPanel';
|
||||
import { SaveQueryDialog, SaveAlertDialog } from './SaveQueryDialog';
|
||||
import { QueryHistoryPanel } from './QueryHistoryPanel';
|
||||
import { SavedQueriesPanel } from './SavedQueriesPanel';
|
||||
import { LogAlertFromQueryDialog } from './LogAlertFromQueryDialog';
|
||||
import { logCenterApi, type LogDataSource } from '@/api';
|
||||
import type { LogEngine, TimeRange, ResultTab, ViewMode, LogEntry, StatTable, LogCluster, QueryHistoryItem } from './types-v3';
|
||||
import { QueryAutocompleteInput } from './QueryAutocompleteInput';
|
||||
import { QuickQueryBar } from './QuickQueryBar';
|
||||
import { parseLogQueryUrl, buildLogQueryParams, buildShareUrl } from './query-url-state';
|
||||
import { logCenterApi, type LogDataSource, type LogQueryEntry } from '@/api';
|
||||
import { copyToClipboard } from '@/utils/clipboard';
|
||||
import { buildLogCopyText, formatHistogramCount, formatHistogramTick, formatLogTimestamp } from './log-format';
|
||||
import { EsIndexPicker } from './EsIndexPicker';
|
||||
import { LokiLabelBrowser } from './LokiLabelBrowser';
|
||||
import { applyESFieldFilter, applyLokiLabelFilter, extractLokiSelector } from './query-builder';
|
||||
import type { LogEngine, TimeRange, ResultTab, ViewMode, LogEntry, LogField, StatTable, LogCluster, QueryHistoryItem, SavedQuery } from './types-v3';
|
||||
import { ENGINE_META, buildStatTableFromEntries, buildClustersFromEntries, extractFields, generateHistogramData, historyStorage } from './types-v3';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
|
||||
@@ -37,104 +47,14 @@ const ENGINE_BADGE: Record<'loki' | 'elasticsearch', { label: string; dotColor:
|
||||
elasticsearch: { label: 'Lucene', dotColor: '#22c55e' },
|
||||
};
|
||||
|
||||
// 增强快捷查询模板(14+ 条/引擎) // Logan.Li
|
||||
const ALL_TEMPLATES: Record<'loki' | 'elasticsearch', { label: string; query: string }[]> = {
|
||||
loki: [
|
||||
{ label: 'Nginx 错误', query: '{job="nginx"} |= "error"' },
|
||||
{ label: 'JSON 过滤', query: '{namespace="prod"} | json | level="warn"' },
|
||||
{ label: '超时搜索', query: '{app="api"} |= "timeout"' },
|
||||
{ label: '级别统计', query: 'sum by(level) (count_over_time({job="app"}[5m]))' },
|
||||
{ label: '正则多级别', query: '{container="frontend"} |~ "ERROR|WARN|FATAL"' },
|
||||
{ label: '慢请求>1s', query: '{job="api"} | json | response_time > 1000' },
|
||||
{ label: '错误率统计', query: 'sum by(level) (count_over_time({app="cex-admin-api"} |= "error" [5m]))' },
|
||||
{ label: '追踪ID查询', query: '{app="cex-admin-api"} |= "trace_id" | json' },
|
||||
{ label: '服务聚合', query: 'sum by(service_name) (count_over_time({namespace="astralx"}[5m]))' },
|
||||
{ label: '高延迟筛选', query: '{app="cex-admin-api"} | json | response_time > 500' },
|
||||
{ label: '异常堆栈', query: '{app="cex-admin-api"} |= "Exception"' },
|
||||
{ label: '日志趋势', query: 'sum(count_over_time({app="cex-admin-api"}[1h]))' },
|
||||
{ label: '正则提取', query: '{app="cex-admin-api"} | regexp "(?P<method>[A-Za-z0-9_]+) (?P<path>[^ ]+)"' }, // LogQL regexp 用 RE2,不支持 \w \S 等 Perl 简写,须用显式字符类,否则 Loki 返回 400 invalid char escape // Logan.Li
|
||||
{ label: '格式输出', query: '{app="cex-admin-api"} | json | line_format "{{.level}} {{.message}}"' },
|
||||
],
|
||||
elasticsearch: [
|
||||
{ label: 'API 5xx', query: 'status:500 AND path:"/api/*"' },
|
||||
{ label: '错误超时', query: 'level:error AND message:*timeout*' },
|
||||
{ label: '排除调试', query: 'host.name:server-* AND NOT level:debug' },
|
||||
{ label: '慢请求', query: 'response_time:>1000 AND method:POST' },
|
||||
{ label: '严重错误', query: '@timestamp:[now-1h TO now] AND level:critical' },
|
||||
{ label: '服务错误', query: 'service:nginx AND (level:error OR level:fatal)' },
|
||||
{ label: '组合查询', query: 'app:cex-admin-api AND (level:error OR level:warn)' },
|
||||
{ label: '模糊匹配', query: 'message:*timeout* AND app:cex-admin-api' },
|
||||
{ label: '范围查询', query: 'response_time:[1000 TO *] AND method:POST' },
|
||||
{ label: '排除路径', query: 'app:cex-admin-api AND NOT path:/health' },
|
||||
{ label: '时间过滤', query: '@timestamp:[now-1h TO now] AND level:error' },
|
||||
{ label: 'IP段过滤', query: 'client_ip:172.36.* AND app:cex-admin-api' },
|
||||
{ label: '聚合统计', query: 'app:cex-admin-api | STATS count(*) by level' },
|
||||
{ label: '嵌套字段', query: 'labels.orgId:10001 AND app:cex-admin-api' },
|
||||
],
|
||||
};
|
||||
|
||||
// LogQL / Lucene 语法高亮 → HTML // Logan.Li
|
||||
function highlightSyntax(query: string, engine: 'loki' | 'elasticsearch'): string {
|
||||
if (!query) return '<span style="color:transparent">.</span>';
|
||||
// 先转义 HTML 特殊字符,避免查询语句中的 < > & 破坏标签结构 // Logan.Li
|
||||
const esc = query.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const span = (color: string, text: string) => `<span style="color:${color}">${text}</span>`;
|
||||
if (engine === 'loki') {
|
||||
// 单正则 + 回调:一次匹配,避免链式 replace 对已生成颜色值的二次匹配 // Logan.Li
|
||||
return esc.replace(
|
||||
/("(?:[^"\\]|\\.)*")|([a-zA-Z_][\w-]*)(?==)|(\|json|\|regexp|\|line_format|\|unwrap|\|pattern|\|label_format)|\b(count_over_time|sum|rate|avg|max|min|count|by|over)\b|([{}])|(\|=|\!=|=~|!~|=)/g,
|
||||
(m, str, ident, pipe, fn, brace, op) => {
|
||||
if (str) return span('#22c55e', str);
|
||||
if (ident) return span('#f59e0b', ident);
|
||||
if (pipe) return span('#8b5cf6', pipe);
|
||||
if (fn) return span('#06b6d4', fn);
|
||||
if (brace) return span('#f59e0b', brace);
|
||||
if (op) return span('#f43f5e', op);
|
||||
return m;
|
||||
},
|
||||
) + '<span style="color:transparent">.</span>';
|
||||
}
|
||||
return esc.replace(
|
||||
/("(?:[^"\\]|\\.)*")|\b(AND|OR|NOT)\b|([a-zA-Z_@][\w.-]*)(?=:)|([*?~^[\]()])/g,
|
||||
(m, str, kw, field, punct) => {
|
||||
if (str) return span('#22c55e', str);
|
||||
if (kw) return span('#f43f5e', kw);
|
||||
if (field) return span('#f59e0b', field);
|
||||
if (punct) return span('#8b5cf6', punct);
|
||||
return m;
|
||||
},
|
||||
) + '<span style="color:transparent">.</span>';
|
||||
}
|
||||
|
||||
// 语法高亮输入框:底层高亮 + 上层透明输入 // Logan.Li
|
||||
function SyntaxHighlightInput({ value, onChange, engine, placeholder }: {
|
||||
value: string; onChange: (v: string) => void; engine: 'loki' | 'elasticsearch'; placeholder?: string;
|
||||
}) {
|
||||
const taRef = useRef<HTMLTextAreaElement>(null);
|
||||
const preRef = useRef<HTMLPreElement>(null);
|
||||
const sync = useCallback(() => {
|
||||
if (preRef.current && taRef.current) { preRef.current.scrollLeft = taRef.current.scrollLeft; preRef.current.scrollTop = taRef.current.scrollTop; }
|
||||
}, []);
|
||||
const onKey = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Tab') { e.preventDefault(); const t = e.currentTarget, s = t.selectionStart, ed = t.selectionEnd; onChange(value.slice(0, s) + ' ' + value.slice(ed)); requestAnimationFrame(() => { t.selectionStart = t.selectionEnd = s + 2; }); }
|
||||
};
|
||||
const html = useMemo(() => highlightSyntax(value, engine), [value, engine]);
|
||||
return (
|
||||
<div className="relative flex-1 min-w-[120px]" style={{ height: '40px', background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', borderRadius: '0.25rem' }}>
|
||||
<textarea ref={taRef} value={value} onChange={e => onChange(e.target.value)} onScroll={sync} onKeyDown={onKey} spellCheck={false} autoComplete="off" rows={1}
|
||||
className="absolute inset-0 w-full h-full font-mono text-xs rounded resize-none outline-none overflow-auto whitespace-pre-wrap break-all px-3 py-2.5"
|
||||
style={{ background: 'transparent', color: 'transparent', caretColor: 'var(--dg-text-primary)', lineHeight: '20px', zIndex: 1 }}
|
||||
placeholder={placeholder} />
|
||||
<pre ref={preRef} className="absolute inset-0 m-0 font-mono text-xs rounded pointer-events-none overflow-hidden whitespace-pre-wrap break-all px-3 py-2.5" style={{ background: 'transparent', lineHeight: '20px', color: 'var(--dg-text-primary)', zIndex: 2 }} dangerouslySetInnerHTML={{ __html: html }} />
|
||||
{!value && <div className="absolute inset-0 flex items-center px-3 pointer-events-none" style={{ zIndex: 3 }}><span className="text-xs font-mono" style={{ color: 'var(--dg-text-muted)' }}>{placeholder}</span></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props { engine: LogEngine; onRuleCreated: () => void; }
|
||||
|
||||
export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
const { toast } = useToast();
|
||||
const location = useLocation();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const urlBootstrapped = useRef(false);
|
||||
const autoRunDone = useRef(false);
|
||||
const effEngine: 'loki' | 'elasticsearch' = engine === 'sls' ? 'loki' : engine;
|
||||
const meta = ENGINE_META[effEngine];
|
||||
const badge = ENGINE_BADGE[effEngine];
|
||||
@@ -164,8 +84,8 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
const [queryTime, setQueryTime] = useState(0);
|
||||
const [resultTab, setResultTab] = useState<ResultTab>('logs');
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('raw');
|
||||
const [wrapLines, setWrapLines] = useState(false);
|
||||
const [truncate, setTruncate] = useState(true);
|
||||
const [wrapLines, setWrapLines] = useState(true);
|
||||
const [truncate, setTruncate] = useState(false);
|
||||
const [selectedFields, setSelectedFields] = useState<string[]>([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(20);
|
||||
@@ -176,17 +96,74 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
const [alertDialogOpen, setAlertDialogOpen] = useState(false);
|
||||
const [saveMenuOpen, setSaveMenuOpen] = useState(false);
|
||||
const [hasQueried, setHasQueried] = useState(false);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [nextCursor, setNextCursor] = useState('');
|
||||
const [searchAfter, setSearchAfter] = useState<unknown[] | undefined>();
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [liveTail, setLiveTail] = useState(false);
|
||||
const [savedPanelOpen, setSavedPanelOpen] = useState(false);
|
||||
const [labelNames, setLabelNames] = useState<string[]>([]);
|
||||
const [labelValues, setLabelValues] = useState<string[]>([]);
|
||||
const [indexedFields, setIndexedFields] = useState<LogField[]>([]);
|
||||
|
||||
// 数据源加载后选中默认或首个(无源时保持空),并同步 ES 默认索引 // Logan.Li
|
||||
const timeIsoParams = useCallback(() => ({
|
||||
start: timeRange.start.replace(' ', 'T'),
|
||||
end: timeRange.end.replace(' ', 'T'),
|
||||
}), [timeRange]);
|
||||
|
||||
const currentSource = sources.find((s) => String(s.id) === dsId);
|
||||
|
||||
// 数据源加载后选中默认或首个;首次从 URL 恢复查询状态 // Logan.Li
|
||||
useEffect(() => {
|
||||
if (sources.length > 0) {
|
||||
const def = sources.find(s => s.is_default) || sources[0];
|
||||
if (sources.length === 0) return;
|
||||
if (!urlBootstrapped.current) {
|
||||
const parsed = parseLogQueryUrl(searchParams);
|
||||
const def = sources.find((s) => String(s.id) === parsed.datasourceId)
|
||||
|| sources.find((s) => s.is_default) || sources[0];
|
||||
setDsId(String(def.id));
|
||||
setEsIndex(def.default_index || '');
|
||||
setEsIndex(parsed.index || def.default_index || '');
|
||||
if (parsed.query) setQuery(parsed.query);
|
||||
if (parsed.timeRange) setTimeRange(parsed.timeRange);
|
||||
urlBootstrapped.current = true;
|
||||
return;
|
||||
}
|
||||
}, [sources]);
|
||||
const def = sources.find((s) => String(s.id) === dsId) || sources.find((s) => s.is_default) || sources[0];
|
||||
if (!dsId && def) setDsId(String(def.id));
|
||||
}, [sources, searchParams, dsId]);
|
||||
|
||||
const currentSource = sources.find(s => String(s.id) === dsId);
|
||||
// 查询状态同步到 URL(可分享)// Logan.Li
|
||||
useEffect(() => {
|
||||
if (!urlBootstrapped.current) return;
|
||||
const p = buildLogQueryParams({
|
||||
query,
|
||||
datasourceId: dsId || undefined,
|
||||
index: esIndex || undefined,
|
||||
timeRange,
|
||||
});
|
||||
setSearchParams(p, { replace: true });
|
||||
}, [query, dsId, esIndex, timeRange, setSearchParams]);
|
||||
|
||||
// Loki 标签名(自动补全)// Logan.Li
|
||||
useEffect(() => {
|
||||
if (effEngine !== 'loki' || !currentSource?.id) return;
|
||||
logCenterApi.listLokiLabels(currentSource.id, timeIsoParams())
|
||||
.then((res) => setLabelNames(Array.isArray(res) ? res : []))
|
||||
.catch(() => setLabelNames([]));
|
||||
}, [effEngine, currentSource?.id, timeIsoParams]);
|
||||
|
||||
// ES mapping 索引字段(Kibana 风格侧栏)// Logan.Li
|
||||
useEffect(() => {
|
||||
if (effEngine !== 'elasticsearch' || !currentSource?.id) return;
|
||||
logCenterApi.esMapping({ datasource_id: currentSource.id, index: esIndex || undefined })
|
||||
.then((res) => {
|
||||
const list = Array.isArray(res) ? res : [];
|
||||
setIndexedFields(list.map((f) => ({
|
||||
name: f.name,
|
||||
type: (['keyword', 'long', 'date', 'boolean', 'ip'].includes(f.type) ? f.type : 'text') as LogField['type'],
|
||||
})));
|
||||
})
|
||||
.catch(() => setIndexedFields([]));
|
||||
}, [effEngine, currentSource?.id, esIndex]);
|
||||
|
||||
const fields = useMemo(() => extractFields(entries), [entries]);
|
||||
const commonLabels = useMemo(() => extractCommonLabels(entries), [entries]);
|
||||
@@ -194,55 +171,92 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
const totalPages = Math.max(1, Math.ceil(sortedEntries.length / perPage));
|
||||
const pagedEntries = useMemo(() => { const s = (page - 1) * perPage; return sortedEntries.slice(s, s + perPage); }, [sortedEntries, page, perPage]);
|
||||
|
||||
const mapRawEntries = useCallback((rawEntries: LogQueryEntry[]): LogEntry[] => rawEntries.map((e) => {
|
||||
const raw = String(e.raw || e.message || '');
|
||||
let level = String(e.level || e.labels?.detected_level || e.labels?.level || '');
|
||||
if (!level && effEngine === 'elasticsearch' && raw) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Record<string, unknown>;
|
||||
level = String(parsed.level || parsed['log.level'] || (parsed.log as Record<string, unknown>)?.level || '');
|
||||
} catch { /* 非 JSON */ }
|
||||
}
|
||||
if (!level) {
|
||||
const levelMatch = raw.match(/\s(INFO|WARN|WARNING|ERROR|DEBUG|TRACE|FATAL)\s/i);
|
||||
if (levelMatch) level = levelMatch[1].toLowerCase();
|
||||
}
|
||||
const labels = e.labels || {};
|
||||
return {
|
||||
timestamp: formatLogTimestamp(e.timestamp || ''),
|
||||
level,
|
||||
message: String(e.message || raw),
|
||||
labels,
|
||||
raw,
|
||||
source: labels.app || labels.service_name || '',
|
||||
};
|
||||
}), [effEngine]);
|
||||
|
||||
const fetchHistogram = useCallback(async (dsIdNum: number, startISO: string, endISO: string) => {
|
||||
try {
|
||||
if (effEngine === 'loki') {
|
||||
const res = await logCenterApi.lokiHistogram({ datasource_id: dsIdNum, query, start: startISO, end: endISO });
|
||||
const buckets = res?.buckets || [];
|
||||
if (buckets.length > 0) {
|
||||
setHistogramData(buckets.map((b) => ({
|
||||
timestamp: formatLogTimestamp(b.timestamp),
|
||||
count: b.count,
|
||||
})));
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
const res = await logCenterApi.esHistogram({
|
||||
datasource_id: dsIdNum, query, index: esIndex || undefined, start: startISO, end: endISO,
|
||||
});
|
||||
const buckets = res?.buckets || [];
|
||||
if (buckets.length > 0) {
|
||||
setHistogramData(buckets.map((b) => ({
|
||||
timestamp: formatLogTimestamp(b.timestamp),
|
||||
count: b.count,
|
||||
})));
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch { /* 直方图失败时回退客户端聚合 */ }
|
||||
}, [effEngine, query, esIndex]);
|
||||
|
||||
// 执行查询 — 接入真实 API(无 mock)// Logan.Li
|
||||
const handleRun = useCallback(async () => {
|
||||
// 空查询兜底:后端 Query 字段 required,空值会 400,这里提前拦截 // Logan.Li
|
||||
if (!currentSource || !query.trim()) return;
|
||||
const dsIdNum = currentSource.id;
|
||||
setLoading(true);
|
||||
setHasMore(false);
|
||||
setNextCursor('');
|
||||
setSearchAfter(undefined);
|
||||
const t0 = performance.now();
|
||||
|
||||
try {
|
||||
const startISO = (timeRange.start + (timeRange.start.includes('T') ? '' : '.000Z')).replace(' ', 'T');
|
||||
const endISO = (timeRange.end + (timeRange.end.includes('T') ? '' : '.000Z')).replace(' ', 'T');
|
||||
let result: any;
|
||||
|
||||
if (effEngine === 'loki') {
|
||||
result = await logCenterApi.queryLoki({
|
||||
datasource_id: dsIdNum,
|
||||
query,
|
||||
limit: queryLimit,
|
||||
start: startISO,
|
||||
end: endISO,
|
||||
direction: 'backward',
|
||||
const data = effEngine === 'loki'
|
||||
? await logCenterApi.queryLoki({
|
||||
datasource_id: dsIdNum, query, limit: queryLimit, start: startISO, end: endISO, direction: 'backward',
|
||||
})
|
||||
: await logCenterApi.queryElasticsearch({
|
||||
datasource_id: dsIdNum, index: esIndex || undefined, query, size: queryLimit, start: startISO, end: endISO,
|
||||
});
|
||||
} else {
|
||||
result = await logCenterApi.queryElasticsearch({
|
||||
datasource_id: dsIdNum,
|
||||
index: esIndex || undefined,
|
||||
query,
|
||||
size: queryLimit,
|
||||
start: startISO,
|
||||
end: endISO,
|
||||
});
|
||||
}
|
||||
|
||||
const data = (result as any)?.data || result;
|
||||
const rawEntries: any[] = data?.entries || [];
|
||||
const mapped: LogEntry[] = rawEntries.map((e: any) => ({
|
||||
timestamp: e.timestamp || '',
|
||||
level: e.level || '',
|
||||
message: e.message || '',
|
||||
labels: e.labels || {},
|
||||
raw: e.raw || e.message || '',
|
||||
source: e.labels?.app || e.labels?.service_name || '',
|
||||
}));
|
||||
const rawEntries = data?.entries || [];
|
||||
const mapped = mapRawEntries(rawEntries);
|
||||
|
||||
setEntries(mapped);
|
||||
void fetchHistogram(dsIdNum, startISO, endISO);
|
||||
setHistogramData(generateHistogramData(mapped));
|
||||
setTotalCount(data?.total || mapped.length);
|
||||
setTotalCount(data?.total ?? mapped.length);
|
||||
setHasMore(!!data?.has_more);
|
||||
setNextCursor(data?.next_cursor || '');
|
||||
setSearchAfter(data?.search_after);
|
||||
setQueryTime(Math.round(performance.now() - t0));
|
||||
// 统计图表 / 聚类基于真实返回条目聚合(无 mock)// Logan.Li
|
||||
setStatTable(buildStatTableFromEntries(mapped));
|
||||
setClusters(buildClustersFromEntries(mapped));
|
||||
setPage(1);
|
||||
@@ -259,7 +273,139 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [effEngine, query, currentSource, timeRange, toast, queryLimit, esIndex]);
|
||||
}, [effEngine, query, currentSource, timeRange, toast, queryLimit, esIndex, mapRawEntries, fetchHistogram]);
|
||||
|
||||
const handleLoadMore = useCallback(async () => {
|
||||
if (!currentSource || !hasMore || loadingMore) return;
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
const startISO = (timeRange.start + (timeRange.start.includes('T') ? '' : '.000Z')).replace(' ', 'T');
|
||||
const endISO = (timeRange.end + (timeRange.end.includes('T') ? '' : '.000Z')).replace(' ', 'T');
|
||||
const dsIdNum = currentSource.id;
|
||||
const data = effEngine === 'loki'
|
||||
? await logCenterApi.queryLoki({
|
||||
datasource_id: dsIdNum, query, limit: queryLimit, start: startISO, end: endISO,
|
||||
direction: 'backward', cursor: nextCursor,
|
||||
})
|
||||
: await logCenterApi.queryElasticsearch({
|
||||
datasource_id: dsIdNum, index: esIndex || undefined, query, size: queryLimit,
|
||||
start: startISO, end: endISO, search_after: searchAfter,
|
||||
});
|
||||
const more = mapRawEntries(data?.entries || []);
|
||||
setEntries((prev) => {
|
||||
const merged = [...prev, ...more];
|
||||
setStatTable(buildStatTableFromEntries(merged));
|
||||
setClusters(buildClustersFromEntries(merged));
|
||||
return merged;
|
||||
});
|
||||
setHasMore(!!data?.has_more);
|
||||
setNextCursor(data?.next_cursor || '');
|
||||
setSearchAfter(data?.search_after);
|
||||
} catch (e: unknown) {
|
||||
toast({ title: '加载更多失败', description: (e as Error)?.message, variant: 'destructive' });
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, [currentSource, hasMore, loadingMore, effEngine, query, queryLimit, timeRange, esIndex, nextCursor, searchAfter, mapRawEntries, toast]);
|
||||
|
||||
const handleLabelFilter = useCallback((key: string, value: string, op: 'include' | 'exclude') => {
|
||||
if (effEngine === 'loki') {
|
||||
setQuery((q) => applyLokiLabelFilter(q, key, value, op));
|
||||
} else {
|
||||
setQuery((q) => applyESFieldFilter(q, key, value, op));
|
||||
}
|
||||
}, [effEngine]);
|
||||
|
||||
const handleRequestLabelValues = useCallback((label: string) => {
|
||||
if (!currentSource?.id) return;
|
||||
const selector = extractLokiSelector(query);
|
||||
logCenterApi.listLokiLabelValues(currentSource.id, label, {
|
||||
...timeIsoParams(),
|
||||
...(selector ? { query: selector } : {}),
|
||||
})
|
||||
.then((res) => setLabelValues(Array.isArray(res) ? res : []))
|
||||
.catch(() => setLabelValues([]));
|
||||
}, [currentSource?.id, timeIsoParams, query]);
|
||||
|
||||
const handleFieldClick = useCallback((field: string) => {
|
||||
if (effEngine === 'elasticsearch') {
|
||||
setQuery((q) => applyESFieldFilter(q, field, '*', 'include'));
|
||||
} else {
|
||||
setQuery((q) => `${q} ${field}=""`.trim());
|
||||
}
|
||||
}, [effEngine]);
|
||||
|
||||
const handleShareLink = useCallback(async () => {
|
||||
const url = buildShareUrl(location.pathname, {
|
||||
query, datasourceId: dsId, index: esIndex || undefined, timeRange,
|
||||
}, true);
|
||||
const full = `${window.location.origin}${url}`;
|
||||
const ok = await copyToClipboard(full);
|
||||
toast({
|
||||
title: ok ? '分享链接已复制' : '复制失败',
|
||||
description: ok ? '收件人打开链接将自动执行查询' : undefined,
|
||||
variant: ok ? 'default' : 'destructive',
|
||||
});
|
||||
}, [location.pathname, query, dsId, esIndex, timeRange, toast]);
|
||||
|
||||
const runLiveTailTick = useCallback(async () => {
|
||||
if (!currentSource || !query.trim()) return;
|
||||
const now = new Date();
|
||||
const start = new Date(now.getTime() - 5 * 60000);
|
||||
const tr: TimeRange = {
|
||||
start: start.toISOString().replace('T', ' ').substring(0, 19),
|
||||
end: now.toISOString().replace('T', ' ').substring(0, 19),
|
||||
label: 'Live',
|
||||
type: 'relative',
|
||||
};
|
||||
setTimeRange(tr);
|
||||
const startISO = tr.start.replace(' ', 'T');
|
||||
const endISO = tr.end.replace(' ', 'T');
|
||||
try {
|
||||
const data = effEngine === 'loki'
|
||||
? await logCenterApi.queryLoki({
|
||||
datasource_id: currentSource.id, query, limit: 200, start: startISO, end: endISO, direction: 'backward',
|
||||
})
|
||||
: await logCenterApi.queryElasticsearch({
|
||||
datasource_id: currentSource.id, index: esIndex || undefined, query, size: 200, start: startISO, end: endISO,
|
||||
});
|
||||
const mapped = mapRawEntries(data?.entries || []);
|
||||
setEntries((prev) => {
|
||||
const keys = new Set(prev.map((e) => `${e.timestamp}|${e.message}`));
|
||||
const fresh = mapped.filter((e) => !keys.has(`${e.timestamp}|${e.message}`));
|
||||
if (fresh.length === 0) return prev;
|
||||
const merged = [...fresh, ...prev].slice(0, 2000);
|
||||
setStatTable(buildStatTableFromEntries(merged));
|
||||
setClusters(buildClustersFromEntries(merged));
|
||||
setTotalCount(merged.length);
|
||||
setHasQueried(true);
|
||||
return merged;
|
||||
});
|
||||
} catch { /* Live tail 静默失败 */ }
|
||||
}, [currentSource, query, effEngine, esIndex, mapRawEntries]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!liveTail) return undefined;
|
||||
void runLiveTailTick();
|
||||
const id = setInterval(() => { void runLiveTailTick(); }, 3000);
|
||||
return () => clearInterval(id);
|
||||
}, [liveTail, runLiveTailTick]);
|
||||
|
||||
const handleRunRef = useRef(handleRun);
|
||||
handleRunRef.current = handleRun;
|
||||
useEffect(() => {
|
||||
if (!urlBootstrapped.current || autoRunDone.current) return;
|
||||
if (searchParams.get('run') !== '1' || !currentSource || !query.trim()) return;
|
||||
autoRunDone.current = true;
|
||||
void handleRunRef.current();
|
||||
}, [currentSource, query, searchParams]);
|
||||
|
||||
const handleSavedQuerySelect = useCallback((item: SavedQuery) => {
|
||||
setQuery(item.query);
|
||||
if (String(item.datasourceId) !== dsId) setDsId(String(item.datasourceId));
|
||||
}, [dsId]);
|
||||
|
||||
const mappingFieldNames = useMemo(() => indexedFields.map((f) => f.name), [indexedFields]);
|
||||
|
||||
const toggleField = useCallback((n: string) => setSelectedFields(p => p.includes(n) ? p.filter(f => f !== n) : [...p, n]), []);
|
||||
const handleSaveMenu = (a: 'query' | 'alert') => { setSaveMenuOpen(false); a === 'query' ? setSaveQueryOpen(true) : setSaveAlertOpen(true); };
|
||||
@@ -272,6 +418,30 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
setTimeRange(p => ({ ...p, start: histogramData[sIdx].timestamp, end: histogramData[eIdx].timestamp, label: '自定义', type: 'absolute' as const }));
|
||||
}, [histogramData]);
|
||||
|
||||
const formatEntryLine = useCallback((e: LogEntry) => buildLogCopyText(e), []);
|
||||
|
||||
const handleExportLogs = useCallback(() => {
|
||||
const t = sortedEntries.map(formatEntryLine).join('\n');
|
||||
const b = new Blob([t], { type: 'text/plain;charset=utf-8' });
|
||||
const u = URL.createObjectURL(b);
|
||||
const a = document.createElement('a');
|
||||
a.href = u;
|
||||
a.download = `${effEngine}-logs-${Date.now()}.txt`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(u);
|
||||
toast({ title: '已导出', description: `${sortedEntries.length} 条日志` });
|
||||
}, [sortedEntries, effEngine, formatEntryLine, toast]);
|
||||
|
||||
const handleCopyLogs = useCallback(async () => {
|
||||
const text = pagedEntries.map(formatEntryLine).join('\n');
|
||||
const ok = await copyToClipboard(text);
|
||||
if (ok) {
|
||||
toast({ title: '已复制', description: `当前页 ${pagedEntries.length} 条完整日志` });
|
||||
} else {
|
||||
toast({ title: '复制失败', description: '请使用导出或展开单条复制', variant: 'destructive' });
|
||||
}
|
||||
}, [pagedEntries, formatEntryLine, toast]);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* ===== 查询控制行 ===== */}
|
||||
@@ -281,10 +451,32 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
<span className="w-2 h-2 rounded-full" style={{ background: badge.dotColor }} />
|
||||
<span className="text-[11px] font-semibold" style={{ color: badge.dotColor }}>{badge.label}</span>
|
||||
</div>
|
||||
<SyntaxHighlightInput value={query} onChange={setQuery} engine={effEngine} placeholder={meta.queryPlaceholder} />
|
||||
<button onClick={handleRun} disabled={loading || !currentSource || !query.trim()} className="h-10 px-4 rounded text-xs font-medium text-white flex items-center gap-1.5 flex-shrink-0 transition-opacity hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed" style={{ background: '#22c55e' }}>
|
||||
<QueryAutocompleteInput
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
engine={effEngine}
|
||||
placeholder={meta.queryPlaceholder}
|
||||
labelNames={labelNames}
|
||||
labelValues={labelValues}
|
||||
mappingFields={mappingFieldNames}
|
||||
onRequestLabelValues={handleRequestLabelValues}
|
||||
/>
|
||||
<button onClick={() => { setLiveTail(false); void handleRun(); }} disabled={loading || liveTail || !currentSource || !query.trim()} className="h-10 px-4 rounded text-xs font-medium text-white flex items-center gap-1.5 flex-shrink-0 transition-opacity hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed" style={{ background: '#22c55e' }}>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />} 查询
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setLiveTail((v) => !v)}
|
||||
disabled={!currentSource || !query.trim()}
|
||||
className="h-10 px-3 rounded text-xs flex items-center gap-1 flex-shrink-0"
|
||||
style={{
|
||||
border: `1px solid ${liveTail ? '#ef4444' : 'var(--dg-border)'}`,
|
||||
color: liveTail ? '#ef4444' : 'var(--dg-text-secondary)',
|
||||
background: liveTail ? 'rgba(239,68,68,0.1)' : 'var(--dg-bg-tertiary)',
|
||||
}}
|
||||
title="Live Tail — 每 3 秒刷新最近 5 分钟日志"
|
||||
>
|
||||
<Radio className={`h-3.5 w-3.5 ${liveTail ? 'animate-pulse' : ''}`} /> Tail
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/* 次级控件行(时间 / 数据源 / 索引 / 上限 / 另存为 / 历史)// Logan.Li */}
|
||||
@@ -297,13 +489,10 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
</select>
|
||||
|
||||
{effEngine === 'elasticsearch' && (
|
||||
<input
|
||||
<EsIndexPicker
|
||||
datasourceId={currentSource?.id}
|
||||
value={esIndex}
|
||||
onChange={e => setEsIndex(e.target.value)}
|
||||
placeholder="索引通配符"
|
||||
title="临时覆盖数据源默认索引,留空使用数据源配置"
|
||||
className="h-10 px-2 text-xs rounded flex-shrink-0 font-mono"
|
||||
style={{ width: '150px', background: 'var(--dg-bg-tertiary)', border: '1px solid var(--dg-border)', color: 'var(--dg-text-primary)' }}
|
||||
onChange={setEsIndex}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -336,6 +525,12 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
</>)}
|
||||
</div>
|
||||
|
||||
<button onClick={() => { void handleShareLink(); }} className="h-10 px-2.5 flex items-center gap-1 rounded flex-shrink-0 text-xs" style={{ border: '1px solid var(--dg-border)', color: 'var(--dg-text-muted)', background: 'var(--dg-bg-tertiary)' }} title="复制分享链接">
|
||||
<Link2 className="h-3.5 w-3.5" /> 分享
|
||||
</button>
|
||||
<button onClick={() => setSavedPanelOpen(true)} className="h-10 w-10 flex items-center justify-center rounded flex-shrink-0" style={{ border: '1px solid var(--dg-border)', color: 'var(--dg-text-muted)', background: 'var(--dg-bg-tertiary)' }} title="已保存查询">
|
||||
<Bookmark className="h-4 w-4" />
|
||||
</button>
|
||||
<button onClick={() => setHistoryPanelOpen(true)} className="h-10 w-10 flex items-center justify-center rounded flex-shrink-0" style={{ border: '1px solid var(--dg-border)', color: 'var(--dg-text-muted)', background: 'var(--dg-bg-tertiary)' }} title="查询历史">
|
||||
<Clock className="h-4 w-4" />
|
||||
</button>
|
||||
@@ -349,11 +544,20 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
)}
|
||||
|
||||
{/* 快捷查询助手 */}
|
||||
<QuickQueryBar engine={effEngine} templates={ALL_TEMPLATES[effEngine]} onSelect={setQuery} />
|
||||
<QuickQueryBar engine={effEngine} onSelect={setQuery} />
|
||||
|
||||
{effEngine === 'loki' && currentSource && (
|
||||
<LokiLabelBrowser
|
||||
datasourceId={currentSource.id}
|
||||
query={query}
|
||||
timeRange={timeRange}
|
||||
onQueryChange={setQuery}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 统计条 + 工具栏 */}
|
||||
{entries.length > 0 && !loading && (
|
||||
<LogQueryToolbar total={totalCount} queryTime={queryTime} perPage={perPage} onPerPageChange={n => { setPerPage(n); setPage(1); }} page={page} totalPages={totalPages} onPageChange={setPage} sortDirection={sortDirection} onSortToggle={() => setSortDirection(d => d === 'desc' ? 'asc' : 'desc')} onExport={() => { const t = sortedEntries.map(e => `${e.timestamp}\t${e.level || ''}\t${e.message}`).join('\n'); const b = new Blob([t], { type: 'text/plain' }); const u = URL.createObjectURL(b); const a = document.createElement('a'); a.href = u; a.download = `${effEngine}-logs-${Date.now()}.txt`; a.click(); URL.revokeObjectURL(u); }} onCopy={() => navigator.clipboard.writeText(pagedEntries.map(e => `${e.timestamp}\t${e.level || ''}\t${e.message}`).join('\n'))} onBellClick={() => setAlertDialogOpen(true)} />
|
||||
<LogQueryToolbar total={totalCount} queryTime={queryTime} perPage={perPage} onPerPageChange={n => { setPerPage(n); setPage(1); }} page={page} totalPages={totalPages} onPageChange={setPage} sortDirection={sortDirection} onSortToggle={() => setSortDirection(d => d === 'desc' ? 'asc' : 'desc')} onExport={handleExportLogs} onCopy={() => { void handleCopyLogs(); }} onBellClick={() => setAlertDialogOpen(true)} hasMore={hasMore} loadingMore={loadingMore} onLoadMore={() => { void handleLoadMore(); }} />
|
||||
)}
|
||||
|
||||
{/* Log Volume 面积图 */}
|
||||
@@ -368,8 +572,8 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--dg-border)" vertical={false} />
|
||||
<XAxis dataKey="timestamp" tick={{ fontSize: 9, fill: 'var(--dg-text-muted)' }} axisLine={{ stroke: 'var(--dg-border)' }} tickLine={false} tickFormatter={(v: string) => v.slice(-5)} interval="preserveStartEnd" />
|
||||
<YAxis tick={{ fontSize: 9, fill: 'var(--dg-text-muted)' }} axisLine={false} tickLine={false} width={30} />
|
||||
<XAxis dataKey="timestamp" tick={{ fontSize: 9, fill: 'var(--dg-text-muted)' }} axisLine={{ stroke: 'var(--dg-border)' }} tickLine={false} tickFormatter={formatHistogramTick} interval="preserveStartEnd" />
|
||||
<YAxis tick={{ fontSize: 9, fill: 'var(--dg-text-muted)' }} axisLine={false} tickLine={false} width={36} tickFormatter={formatHistogramCount} />
|
||||
<Tooltip contentStyle={{ background: 'var(--dg-bg-secondary)', border: '1px solid var(--dg-border)', borderRadius: '6px', fontSize: '11px', color: 'var(--dg-text-primary)' }} formatter={(v: number) => [`${v} 条日志`, '数量']} labelFormatter={(l: string) => `时间: ${l}`} />
|
||||
<Area type="monotone" dataKey="count" stroke={meta.color} fill={`url(#vol-${effEngine})`} strokeWidth={1.5} dot={false} activeDot={{ r: 4, stroke: meta.color, strokeWidth: 2, fill: 'var(--dg-bg-secondary)' }} />
|
||||
</AreaChart>
|
||||
@@ -395,9 +599,9 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
<div className="p-2">
|
||||
{resultTab === 'logs' && (<>
|
||||
<div className="flex gap-3">
|
||||
<LogFieldSidebar fields={fields} selectedFields={selectedFields} onFieldClick={n => setQuery(p => `${p} ${n}=""`)} onToggleDisplayField={toggleField} loading={loading} />
|
||||
<LogFieldSidebar fields={fields} indexedFields={indexedFields} selectedFields={selectedFields} onFieldClick={handleFieldClick} onToggleDisplayField={toggleField} loading={loading} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<EnhancedLogResults entries={pagedEntries} loading={loading} viewMode={viewMode} wrapLines={wrapLines} truncate={truncate} commonLabels={commonLabels || undefined} />
|
||||
<EnhancedLogResults entries={pagedEntries} loading={loading} viewMode={viewMode} wrapLines={wrapLines} truncate={truncate} commonLabels={commonLabels || undefined} onLabelFilter={handleLabelFilter} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 py-2 px-1">
|
||||
@@ -408,8 +612,8 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="flex items-center gap-1.5 text-[11px] cursor-pointer" style={{ color: 'var(--dg-text-muted)' }}><input type="checkbox" checked={truncate} onChange={e => setTruncate(e.target.checked)} className="h-3.5 w-3.5 rounded" /> 截断</label>
|
||||
<label className="flex items-center gap-1.5 text-[11px] cursor-pointer" style={{ color: 'var(--dg-text-muted)' }}><input type="checkbox" checked={wrapLines} onChange={e => setWrapLines(e.target.checked)} className="h-3.5 w-3.5 rounded" /> 换行</label>
|
||||
<label className="flex items-center gap-1.5 text-[11px] cursor-pointer" style={{ color: 'var(--dg-text-muted)' }} title="开启后折叠行仅显示前 500 字预览"><input type="checkbox" checked={truncate} onChange={e => setTruncate(e.target.checked)} className="h-3.5 w-3.5 rounded" /> 截断预览</label>
|
||||
<label className="flex items-center gap-1.5 text-[11px] cursor-pointer" style={{ color: 'var(--dg-text-muted)' }} title="长日志自动换行显示"><input type="checkbox" checked={wrapLines} onChange={e => setWrapLines(e.target.checked)} className="h-3.5 w-3.5 rounded" /> 换行</label>
|
||||
</div>
|
||||
</>)}
|
||||
{resultTab === 'stats' && <StatChartPanel statTable={statTable} engine={effEngine as LogEngine} query={query} onSaveAsAlert={() => setSaveAlertOpen(true)} onSaveAsQuery={() => setSaveQueryOpen(true)} />}
|
||||
@@ -452,37 +656,11 @@ export function UnifiedQueryPanel({ engine, onRuleCreated }: Props) {
|
||||
)}
|
||||
|
||||
{/* 对话框 */}
|
||||
<SaveQueryDialog open={saveQueryOpen} onClose={() => setSaveQueryOpen(false)} engine={effEngine as LogEngine} query={query} timeRange={timeRange} datasourceName={currentSource?.name} />
|
||||
<SaveQueryDialog open={saveQueryOpen} onClose={() => setSaveQueryOpen(false)} engine={effEngine as LogEngine} query={query} timeRange={timeRange} datasourceId={currentSource?.id} datasourceName={currentSource?.name} />
|
||||
<SavedQueriesPanel visible={savedPanelOpen} onClose={() => setSavedPanelOpen(false)} onSelect={handleSavedQuerySelect} />
|
||||
<SaveAlertDialog open={saveAlertOpen} onClose={() => setSaveAlertOpen(false)} engine={effEngine as LogEngine} query={query} datasourceId={currentSource?.id} datasourceName={currentSource?.name} />
|
||||
<QueryHistoryPanel visible={historyPanelOpen} onClose={() => setHistoryPanelOpen(false)} onSelect={(it: QueryHistoryItem) => { setQuery(it.query); setHistoryPanelOpen(false); }} onCreateAlert={() => { setSaveAlertOpen(true); setHistoryPanelOpen(false); }} />
|
||||
<LogAlertFromQueryDialog open={alertDialogOpen} onOpenChange={setAlertDialogOpen} ctx={{ engine: effEngine as LogEngine, datasourceId: currentSource?.id, datasourceName: currentSource?.name, query, timeRange: timeRange.label }} onSaved={onRuleCreated} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 内联紧凑版快捷查询助手
|
||||
function QuickQueryBar({ engine, templates, onSelect }: { engine: 'loki' | 'elasticsearch'; templates: { label: string; query: string }[]; onSelect: (q: string) => void; }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const labels: Record<'loki' | 'elasticsearch', string> = { loki: 'LogQL', elasticsearch: 'Lucene' };
|
||||
return (
|
||||
<div>
|
||||
<button onClick={() => setOpen(!open)} className="flex items-center gap-1 text-[11px] px-2 py-1 rounded transition-colors" style={{ color: 'var(--dg-blue)', background: open ? 'var(--dg-bg-tertiary)' : 'transparent' }}>
|
||||
<span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--dg-blue)' }} />
|
||||
{labels[engine]} 快捷查询模板
|
||||
<ChevronDown className="h-3 w-3" style={{ transform: open ? 'rotate(0deg)' : 'rotate(-90deg)', transition: 'transform 0.2s' }} />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="mt-1.5 p-2.5 rounded-lg border" style={{ background: 'var(--dg-bg-secondary)', borderColor: 'var(--dg-border)' }}>
|
||||
<div className="grid grid-cols-3 lg:grid-cols-4 gap-1.5">
|
||||
{templates.map((t, i) => (
|
||||
<button key={i} onClick={() => { onSelect(t.query); setOpen(false); }} className="text-left px-2 py-1.5 rounded border text-[11px] transition-all hover:opacity-80" style={{ background: 'var(--dg-bg-tertiary)', borderColor: 'var(--dg-border)', color: 'var(--dg-text-secondary)' }} title={t.query}>
|
||||
<span className="font-medium block truncate" style={{ color: 'var(--dg-text-primary)' }}>{t.label}</span>
|
||||
<span className="block truncate opacity-60 font-mono mt-0.5 text-[10px]">{t.query}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// log-center-types.ts — 日志中心类型(无状态:仅存连接与告警策略)// Logan.Li
|
||||
|
||||
export type LogCenterTab = 'loki' | 'es' | 'datasources' | 'alerts';
|
||||
export type LogCenterTab = 'loki' | 'es' | 'datasources' | 'alerts' | 'rbac';
|
||||
|
||||
export type LogEngine = 'loki' | 'elasticsearch';
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// log-format.ts — 日志时间戳格式化与展示辅助 // Logan.Li
|
||||
|
||||
/** 将 Loki 纳秒时间戳或 epoch 转为可读 ISO 时间 */
|
||||
export function formatLogTimestamp(ts: string): string {
|
||||
if (!ts) return '';
|
||||
const trimmed = ts.trim();
|
||||
// 已是 ISO / 可读格式
|
||||
if (/[-T:]/.test(trimmed) && !/^\d+$/.test(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
const n = Number(trimmed);
|
||||
if (!Number.isFinite(n)) return trimmed;
|
||||
|
||||
let ms: number;
|
||||
if (n > 1e18) ms = Math.floor(n / 1e6); // 纳秒
|
||||
else if (n > 1e15) ms = Math.floor(n / 1e6); // 纳秒(Loki 常见)
|
||||
else if (n > 1e12) ms = Math.floor(n); // 毫秒
|
||||
else ms = Math.floor(n * 1000); // 秒
|
||||
|
||||
const d = new Date(ms);
|
||||
if (Number.isNaN(d.getTime())) return trimmed;
|
||||
return d.toISOString();
|
||||
}
|
||||
|
||||
/** 直方图 X 轴时间刻度(避免科学计数法原样显示)// Logan.Li */
|
||||
export function formatHistogramTick(ts: string | number): string {
|
||||
const raw = String(ts).trim();
|
||||
if (!raw) return '';
|
||||
if (/^[\d.eE+-]+$/.test(raw)) {
|
||||
const n = Number(raw);
|
||||
if (Number.isFinite(n)) {
|
||||
const ms = n > 1e12 ? n : n * 1000;
|
||||
const d = new Date(ms);
|
||||
if (!Number.isNaN(d.getTime())) {
|
||||
return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
}
|
||||
}
|
||||
}
|
||||
const iso = formatLogTimestamp(raw);
|
||||
const d = new Date(iso);
|
||||
if (!Number.isNaN(d.getTime())) {
|
||||
return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
}
|
||||
return raw.length > 8 ? raw.slice(11, 19) : raw;
|
||||
}
|
||||
|
||||
/** 直方图 Y 轴条数刻度 // Logan.Li */
|
||||
export function formatHistogramCount(v: number): string {
|
||||
if (!Number.isFinite(v)) return String(v);
|
||||
if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M`;
|
||||
if (v >= 1e4) return `${Math.round(v / 1000)}k`;
|
||||
return String(Math.round(v));
|
||||
}
|
||||
|
||||
/** 日志行展示文本(截断仅影响折叠预览,展开始终全文) */
|
||||
export function formatLogPreview(text: string, trunc: boolean, maxLen = 500): string {
|
||||
if (!trunc || text.length <= maxLen) return text;
|
||||
return `${text.slice(0, maxLen)}…`;
|
||||
}
|
||||
|
||||
/** 从 Spring / key=value 日志中提取结构化字段 */
|
||||
export function detectLogFields(raw: string): { name: string; value: string }[] {
|
||||
const fields: { name: string; value: string }[] = [];
|
||||
if (!raw) return fields;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed === 'object' && parsed !== null) {
|
||||
for (const [k, v] of Object.entries(parsed)) {
|
||||
fields.push({ name: k, value: String(v) });
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
} catch { /* 非 JSON */ }
|
||||
|
||||
const kvRegex = /(\w+)=([^,\s]+)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = kvRegex.exec(raw)) !== null) {
|
||||
fields.push({ name: m[1], value: m[2] });
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
/** 组装复制用完整日志行 */
|
||||
export function buildLogCopyText(entry: { timestamp?: string; level?: string; raw?: string; message: string }): string {
|
||||
const body = entry.raw || entry.message || '';
|
||||
const ts = formatLogTimestamp(entry.timestamp || '');
|
||||
const level = entry.level ? ` ${entry.level.toUpperCase()}` : '';
|
||||
return ts ? `${ts}${level} ${body}` : body;
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Loader2, Save } from 'lucide-react';
|
||||
import { matchSampleScopes, SAMPLE_SCOPES, type SampleScopeItem } from './matchLogScope';
|
||||
import type { LogDataSource } from '@/api/log/log-center';
|
||||
|
||||
interface LogRoleCreateDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
datasources: LogDataSource[];
|
||||
saving: boolean;
|
||||
name: string;
|
||||
code: string;
|
||||
engine: string;
|
||||
matchField: string;
|
||||
pattern: string;
|
||||
role: string;
|
||||
datasourceId: string;
|
||||
description: string;
|
||||
onNameChange: (v: string) => void;
|
||||
onCodeChange: (v: string) => void;
|
||||
onEngineChange: (v: string) => void;
|
||||
onMatchFieldChange: (v: string) => void;
|
||||
onPatternChange: (v: string) => void;
|
||||
onRoleChange: (v: string) => void;
|
||||
onDatasourceIdChange: (v: string) => void;
|
||||
onDescriptionChange: (v: string) => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
// 新建日志范围权限弹窗 // Logan.Li
|
||||
export function LogRoleCreateDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
datasources,
|
||||
saving,
|
||||
name,
|
||||
code,
|
||||
engine,
|
||||
matchField,
|
||||
pattern,
|
||||
role,
|
||||
datasourceId,
|
||||
description,
|
||||
onNameChange,
|
||||
onCodeChange,
|
||||
onEngineChange,
|
||||
onMatchFieldChange,
|
||||
onPatternChange,
|
||||
onRoleChange,
|
||||
onDatasourceIdChange,
|
||||
onDescriptionChange,
|
||||
onSubmit,
|
||||
}: LogRoleCreateDialogProps) {
|
||||
const preview = useMemo(
|
||||
() => matchSampleScopes(pattern, matchField, engine, SAMPLE_SCOPES),
|
||||
[pattern, matchField, engine],
|
||||
);
|
||||
|
||||
const patternHint = useMemo(() => {
|
||||
if (!pattern.trim()) {
|
||||
return matchField === 'index' ? '输入正则,匹配 ES 索引名' : `输入正则,匹配 Loki ${matchField} Label`;
|
||||
}
|
||||
try {
|
||||
// eslint-disable-next-line no-new
|
||||
new RegExp(pattern);
|
||||
return preview.length > 0 ? `命中 ${preview.length} 个示例范围` : '无匹配示例';
|
||||
} catch {
|
||||
return '正则语法错误';
|
||||
}
|
||||
}, [pattern, matchField, preview.length]);
|
||||
|
||||
const filteredDS = datasources.filter((ds) => {
|
||||
if (engine === '*') return true;
|
||||
return ds.type === engine;
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md bg-[var(--dg-bg-primary)] border-[var(--dg-border)]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建日志权限</DialogTitle>
|
||||
<DialogDescription className="text-[var(--dg-text-muted)]">
|
||||
按正则匹配 ES 索引或 Loki Label,限制用户可查询的日志范围
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">名称</Label>
|
||||
<Input value={name} onChange={(e) => onNameChange(e.target.value)} placeholder="后端日志" className="h-8 text-sm dg-input" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">标识</Label>
|
||||
<Input value={code} onChange={(e) => onCodeChange(e.target.value)} placeholder="backend-logs" className="h-8 text-sm font-mono dg-input" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">引擎</Label>
|
||||
<Select value={engine} onValueChange={onEngineChange}>
|
||||
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="*">全部引擎</SelectItem>
|
||||
<SelectItem value="loki">Loki</SelectItem>
|
||||
<SelectItem value="elasticsearch">Elasticsearch</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">匹配维度</Label>
|
||||
<Select value={matchField} onValueChange={onMatchFieldChange}>
|
||||
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="index">ES 索引</SelectItem>
|
||||
<SelectItem value="app">Loki app</SelectItem>
|
||||
<SelectItem value="namespace">Loki namespace</SelectItem>
|
||||
<SelectItem value="job">Loki job</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">匹配正则</Label>
|
||||
<Input
|
||||
value={pattern}
|
||||
onChange={(e) => onPatternChange(e.target.value)}
|
||||
placeholder={matchField === 'index' ? 'logstash-.*' : '^cex-.*'}
|
||||
className="h-8 text-sm font-mono dg-input"
|
||||
/>
|
||||
<p className="text-[10px] text-[var(--dg-text-muted)]">{patternHint}</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">数据源(可选)</Label>
|
||||
<Select value={datasourceId || '__all'} onValueChange={(v) => onDatasourceIdChange(v === '__all' ? '' : v)}>
|
||||
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder="全部数据源" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__all">全部数据源</SelectItem>
|
||||
{filteredDS.map((ds) => (
|
||||
<SelectItem key={ds.id} value={String(ds.id)}>{ds.name} ({ds.type})</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">权限级别</Label>
|
||||
<Select value={role} onValueChange={onRoleChange}>
|
||||
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="viewer">查看者 — 只读查询</SelectItem>
|
||||
<SelectItem value="analyst">分析者 — 查询 + 告警</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">说明</Label>
|
||||
<Input value={description} onChange={(e) => onDescriptionChange(e.target.value)} placeholder="可选" className="h-8 text-sm dg-input" />
|
||||
</div>
|
||||
{preview.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{preview.map((s: SampleScopeItem) => (
|
||||
<span key={s.label} className="text-[10px] px-1.5 py-0.5 rounded bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-muted)] font-mono">
|
||||
{s.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
|
||||
<Button onClick={onSubmit} disabled={saving}>
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
|
||||
创建
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// 日志范围正则命中工具(ES 索引 / Loki Label)// Logan.Li
|
||||
|
||||
export interface SampleScopeItem {
|
||||
label: string;
|
||||
value: string;
|
||||
engine: 'loki' | 'elasticsearch';
|
||||
field: 'index' | 'app' | 'namespace' | 'job';
|
||||
}
|
||||
|
||||
export const SAMPLE_SCOPES: SampleScopeItem[] = [
|
||||
{ label: 'logstash-2026.07', value: 'logstash-2026.07', engine: 'elasticsearch', field: 'index' },
|
||||
{ label: 'logstash-2026.06', value: 'logstash-2026.06', engine: 'elasticsearch', field: 'index' },
|
||||
{ label: 'app=cex-admin-api', value: 'cex-admin-api', engine: 'loki', field: 'app' },
|
||||
{ label: 'app=api-gateway', value: 'api-gateway', engine: 'loki', field: 'app' },
|
||||
{ label: 'ns=astralx', value: 'astralx', engine: 'loki', field: 'namespace' },
|
||||
{ label: 'job=promtail', value: 'promtail', engine: 'loki', field: 'job' },
|
||||
];
|
||||
|
||||
export function engineMatches(roleEngine: string, targetEngine: string): boolean {
|
||||
const re = (roleEngine || '*').toLowerCase();
|
||||
if (re === '*' || re === '') return true;
|
||||
return re === targetEngine.toLowerCase();
|
||||
}
|
||||
|
||||
export function matchSampleScopes(
|
||||
pattern: string,
|
||||
matchField: string,
|
||||
engine: string,
|
||||
samples: SampleScopeItem[] = SAMPLE_SCOPES,
|
||||
): SampleScopeItem[] {
|
||||
if (!pattern.trim()) return [];
|
||||
try {
|
||||
const re = new RegExp(pattern);
|
||||
return samples.filter((s) => {
|
||||
if (s.field !== matchField) return false;
|
||||
if (!engineMatches(engine, s.engine)) return false;
|
||||
return re.test(s.value);
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function scopeDisplayLabel(s: SampleScopeItem): string {
|
||||
return s.label;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// 查询输入自动补全上下文检测 // Logan.Li
|
||||
|
||||
import { COMMON_ES_FIELDS, ES_KEYWORD_SUGGESTIONS, LOKI_PIPE_SUGGESTIONS } from './query-syntax';
|
||||
|
||||
export interface AutocompleteContext {
|
||||
prefix: string;
|
||||
replaceStart: number;
|
||||
replaceEnd: number;
|
||||
kind: 'label' | 'value' | 'pipe' | 'field' | 'keyword';
|
||||
labelName?: string;
|
||||
}
|
||||
|
||||
const LOKI_SELECTOR_RE = /\{([^}]*)\}/g;
|
||||
|
||||
export function detectAutocompleteContext(
|
||||
query: string,
|
||||
cursor: number,
|
||||
engine: 'loki' | 'elasticsearch',
|
||||
): AutocompleteContext | null {
|
||||
const before = query.slice(0, cursor);
|
||||
if (engine === 'loki') {
|
||||
if (before.endsWith('|') || before.endsWith('| ')) {
|
||||
return { prefix: '', replaceStart: cursor, replaceEnd: cursor, kind: 'pipe' };
|
||||
}
|
||||
const selectorMatch = [...query.matchAll(LOKI_SELECTOR_RE)].find((m) => {
|
||||
const start = m.index ?? 0;
|
||||
const end = start + m[0].length;
|
||||
return cursor >= start && cursor <= end;
|
||||
});
|
||||
if (!selectorMatch) return null;
|
||||
const inner = selectorMatch[1];
|
||||
const innerStart = (selectorMatch.index ?? 0) + 1;
|
||||
const rel = cursor - innerStart;
|
||||
const innerBefore = inner.slice(0, rel);
|
||||
const valueMatch = innerBefore.match(/([a-zA-Z_][\w.-]*)\s*(=~|!~|=|!=)\s*"?([^"]*)$/);
|
||||
if (valueMatch) {
|
||||
const labelName = valueMatch[1];
|
||||
const valStart = innerStart + innerBefore.length - (valueMatch[3]?.length || 0);
|
||||
return {
|
||||
prefix: valueMatch[3] || '',
|
||||
replaceStart: valStart,
|
||||
replaceEnd: cursor,
|
||||
kind: 'value',
|
||||
labelName,
|
||||
};
|
||||
}
|
||||
const labelMatch = innerBefore.match(/(?:^|,)\s*([a-zA-Z_][\w.-]*)?$/);
|
||||
if (labelMatch) {
|
||||
const partial = labelMatch[1] || '';
|
||||
return {
|
||||
prefix: partial,
|
||||
replaceStart: cursor - partial.length,
|
||||
replaceEnd: cursor,
|
||||
kind: 'label',
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const fieldMatch = before.match(/(?:^|\s)([a-zA-Z_@][\w.-]*)$/);
|
||||
if (fieldMatch) {
|
||||
const partial = fieldMatch[1];
|
||||
return {
|
||||
prefix: partial,
|
||||
replaceStart: cursor - partial.length,
|
||||
replaceEnd: cursor,
|
||||
kind: 'field',
|
||||
};
|
||||
}
|
||||
if (/\b(AND|OR|NOT)\s*$/i.test(before) || before.endsWith(' ')) {
|
||||
return { prefix: '', replaceStart: cursor, replaceEnd: cursor, kind: 'keyword' };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function filterSuggestions(
|
||||
ctx: AutocompleteContext,
|
||||
labels: string[],
|
||||
labelValues: string[],
|
||||
mappingFields: string[],
|
||||
): string[] {
|
||||
const p = ctx.prefix.toLowerCase();
|
||||
const match = (items: string[]) => items.filter((s) => s.toLowerCase().startsWith(p)).slice(0, 20);
|
||||
|
||||
switch (ctx.kind) {
|
||||
case 'label':
|
||||
return match(labels);
|
||||
case 'value':
|
||||
return match(labelValues);
|
||||
case 'pipe':
|
||||
return LOKI_PIPE_SUGGESTIONS;
|
||||
case 'field':
|
||||
return match([...new Set([...mappingFields, ...COMMON_ES_FIELDS])]);
|
||||
case 'keyword':
|
||||
return ES_KEYWORD_SUGGESTIONS;
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function applySuggestion(query: string, ctx: AutocompleteContext, suggestion: string): { text: string; cursor: number } {
|
||||
const left = query.slice(0, ctx.replaceStart);
|
||||
const right = query.slice(ctx.replaceEnd);
|
||||
let insert = suggestion;
|
||||
if (ctx.kind === 'value') {
|
||||
insert = suggestion.includes(' ') ? `"${suggestion}"` : suggestion;
|
||||
} else if (ctx.kind === 'label') {
|
||||
insert = `${suggestion}=`;
|
||||
} else if (ctx.kind === 'field') {
|
||||
insert = `${suggestion}:`;
|
||||
}
|
||||
const text = left + insert + right;
|
||||
return { text, cursor: left.length + insert.length };
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// LogQL / Lucene 查询构建辅助(标签点击过滤)// Logan.Li
|
||||
|
||||
const LOKI_SELECTOR_RE = /\{([^}]*)\}/;
|
||||
|
||||
export function applyLokiLabelFilter(
|
||||
query: string,
|
||||
key: string,
|
||||
value: string,
|
||||
op: 'include' | 'exclude',
|
||||
): string {
|
||||
const trimmed = query.trim();
|
||||
const match = trimmed.match(LOKI_SELECTOR_RE);
|
||||
const clause = op === 'include' ? `${key}="${value}"` : `${key}!="${value}"`;
|
||||
if (match) {
|
||||
const inner = match[1].trim();
|
||||
const withoutKey = inner
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s && !s.startsWith(`${key}=`) && !s.startsWith(`${key}!=`))
|
||||
.join(', ');
|
||||
const nextInner = withoutKey ? `${withoutKey}, ${clause}` : clause;
|
||||
return trimmed.replace(LOKI_SELECTOR_RE, `{${nextInner}}`);
|
||||
}
|
||||
const pipeline = trimmed.startsWith('{') ? '' : trimmed;
|
||||
return pipeline ? `{${clause}} ${pipeline}` : `{${clause}}`;
|
||||
}
|
||||
|
||||
export function applyESFieldFilter(
|
||||
query: string,
|
||||
key: string,
|
||||
value: string,
|
||||
op: 'include' | 'exclude',
|
||||
): string {
|
||||
const token = value.includes(' ') || value.includes(':')
|
||||
? `${key}:"${value.replace(/"/g, '\\"')}"`
|
||||
: `${key}:${value}`;
|
||||
const base = query.trim();
|
||||
if (op === 'exclude') {
|
||||
const neg = `NOT ${token}`;
|
||||
return base ? `${base} AND ${neg}` : neg;
|
||||
}
|
||||
return base ? `${base} AND ${token}` : token;
|
||||
}
|
||||
|
||||
/** 从 LogQL 提取 stream selector(Label API 仅接受 {...} 部分)// Logan.Li */
|
||||
export function extractLokiSelector(query: string): string {
|
||||
const trimmed = query.trim();
|
||||
const match = trimmed.match(LOKI_SELECTOR_RE);
|
||||
return match ? `{${match[1]}}` : '';
|
||||
}
|
||||
|
||||
export function buildLokiSelector(labels: Record<string, string>): string {
|
||||
const parts = Object.entries(labels).map(([k, v]) => `${k}="${v}"`);
|
||||
return `{${parts.join(', ')}}`;
|
||||
}
|
||||
|
||||
export function mergeLokiSelector(query: string, labels: Record<string, string>): string {
|
||||
let q = query.trim();
|
||||
const selector = buildLokiSelector(labels);
|
||||
if (LOKI_SELECTOR_RE.test(q)) {
|
||||
return q.replace(LOKI_SELECTOR_RE, selector);
|
||||
}
|
||||
return `${selector} ${q}`.trim();
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// LogQL / Lucene 语法高亮 // Logan.Li
|
||||
|
||||
export function highlightSyntax(query: string, engine: 'loki' | 'elasticsearch'): string {
|
||||
if (!query) return '<span style="color:transparent">.</span>';
|
||||
const esc = query.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const span = (color: string, text: string) => `<span style="color:${color}">${text}</span>`;
|
||||
if (engine === 'loki') {
|
||||
return esc.replace(
|
||||
/("(?:[^"\\]|\\.)*")|([a-zA-Z_][\w-]*)(?==)|(\|json|\|regexp|\|line_format|\|unwrap|\|pattern|\|label_format)|\b(count_over_time|sum|rate|avg|max|min|count|by|over)\b|([{}])|(\|=|\!=|=~|!~|=)/g,
|
||||
(m, str, ident, pipe, fn, brace, op) => {
|
||||
if (str) return span('#22c55e', str);
|
||||
if (ident) return span('#f59e0b', ident);
|
||||
if (pipe) return span('#8b5cf6', pipe);
|
||||
if (fn) return span('#06b6d4', fn);
|
||||
if (brace) return span('#f59e0b', brace);
|
||||
if (op) return span('#f43f5e', op);
|
||||
return m;
|
||||
},
|
||||
) + '<span style="color:transparent">.</span>';
|
||||
}
|
||||
return esc.replace(
|
||||
/("(?:[^"\\]|\\.)*")|\b(AND|OR|NOT)\b|([a-zA-Z_@][\w.-]*)(?=:)|([*?~^[\]()])/g,
|
||||
(m, str, kw, field, punct) => {
|
||||
if (str) return span('#22c55e', str);
|
||||
if (kw) return span('#f43f5e', kw);
|
||||
if (field) return span('#f59e0b', field);
|
||||
if (punct) return span('#8b5cf6', punct);
|
||||
return m;
|
||||
},
|
||||
) + '<span style="color:transparent">.</span>';
|
||||
}
|
||||
|
||||
export const LOKI_PIPE_SUGGESTIONS = ['|= ', '!= ', '|~ ', '!~ ', '| json', '| regexp ', '| line_format ', '| unwrap ', '| pattern '];
|
||||
|
||||
export const ES_KEYWORD_SUGGESTIONS = ['AND ', 'OR ', 'NOT '];
|
||||
|
||||
export const COMMON_ES_FIELDS = [
|
||||
'message', 'level', 'log.level', 'app', 'service', 'host.name', '@timestamp',
|
||||
'kubernetes.namespace', 'trace_id', 'status', 'method', 'path',
|
||||
];
|
||||
@@ -0,0 +1,52 @@
|
||||
// 日志查询 URL 状态编解码 — 可分享链接 // Logan.Li
|
||||
|
||||
import type { TimeRange } from './types-v3';
|
||||
|
||||
export interface LogQueryUrlState {
|
||||
query?: string;
|
||||
datasourceId?: string;
|
||||
index?: string;
|
||||
timeRange?: TimeRange;
|
||||
autoRun?: boolean;
|
||||
}
|
||||
|
||||
export function parseLogQueryUrl(params: URLSearchParams): LogQueryUrlState {
|
||||
const query = params.get('q') || undefined;
|
||||
const datasourceId = params.get('ds') || undefined;
|
||||
const index = params.get('index') || undefined;
|
||||
const start = params.get('from') || undefined;
|
||||
const end = params.get('to') || undefined;
|
||||
const timeLabel = params.get('tr') || '自定义';
|
||||
const autoRun = params.get('run') === '1';
|
||||
const state: LogQueryUrlState = { query, datasourceId, index, autoRun };
|
||||
if (start && end) {
|
||||
state.timeRange = {
|
||||
start: decodeURIComponent(start),
|
||||
end: decodeURIComponent(end),
|
||||
label: decodeURIComponent(timeLabel),
|
||||
type: params.get('trt') === 'relative' ? 'relative' : 'absolute',
|
||||
};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function buildLogQueryParams(state: LogQueryUrlState): URLSearchParams {
|
||||
const p = new URLSearchParams();
|
||||
if (state.query) p.set('q', state.query);
|
||||
if (state.datasourceId) p.set('ds', state.datasourceId);
|
||||
if (state.index) p.set('index', state.index);
|
||||
if (state.timeRange) {
|
||||
p.set('from', state.timeRange.start);
|
||||
p.set('to', state.timeRange.end);
|
||||
p.set('tr', state.timeRange.label);
|
||||
p.set('trt', state.timeRange.type);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
export function buildShareUrl(pathname: string, state: LogQueryUrlState, autoRun = false): string {
|
||||
const p = buildLogQueryParams(state);
|
||||
if (autoRun) p.set('run', '1');
|
||||
const qs = p.toString();
|
||||
return qs ? `${pathname}?${qs}` : pathname;
|
||||
}
|
||||
@@ -257,11 +257,11 @@ export const QUICK_TEMPLATES: Record<LogEngine, { label: string; query: string }
|
||||
],
|
||||
elasticsearch: [
|
||||
{ label: 'API 5xx 错误', query: 'status:500 AND path:"/api/*"' },
|
||||
{ label: '错误超时日志', query: 'level:error AND message:*timeout*' },
|
||||
{ label: '排除调试日志', query: 'host.name:server-* AND NOT level:debug' },
|
||||
{ label: '错误超时日志', query: '(level:error OR log.level:error) AND message:*timeout*' },
|
||||
{ label: '排除调试日志', query: 'host.name:server-* AND NOT level:debug AND NOT log.level:debug' },
|
||||
{ label: '慢请求检测', query: 'response_time:>1000 AND method:POST' },
|
||||
{ label: '最近1小时严重错误', query: '@timestamp:[now-1h TO now] AND level:critical' },
|
||||
{ label: '特定服务错误', query: 'service:nginx AND (level:error OR level:fatal)' },
|
||||
{ label: '最近1小时严重错误', query: '@timestamp:[now-1h TO now] AND (level:critical OR log.level:critical)' },
|
||||
{ label: '特定服务错误', query: 'service:nginx AND (level:(error OR fatal) OR log.level:(error OR fatal))' },
|
||||
],
|
||||
sls: [
|
||||
{ label: '错误日志筛选', query: "* | select * where level = 'error'" },
|
||||
|
||||
Reference in new issue
Block a user