feat(analysis,alerts): 每日量落库看历史趋势、趋势图/饼图可读性、告警三分页
=== 1. 每日日志量必须落库(核心问题:Loki 只留 24 小时)===
实测:请求"近 7 天每日量",Loki 只返回 27 个**小时**桶,全部在最近 24h 内 ——
因为 retention_period=24h,更早的 chunk 已经被删了。
也就是说「固定近 7 天」这张卡片,过去一直是"6 天空白 + 1 天有数据",
用户看着像坏了,实际是数据物理不存在。
方案:平台自己留存历史。
- models.DailyVolumeSnapshot{Date(本地YYYY-MM-DD), SourceID, Bytes, Entries, Partial}
- services/daily_volume.go
CaptureDailyVolume 按天抓 index/stats 落库(幂等覆盖)
StartDailyVolumeCapture 启动 20s 后回补 + 每 30 分钟检查一次
GetDailyVolumeHistory 读库返回最近 N 天(今天会实时补抓)
- 保留 400 天(够看年度趋势),按 source+date 去重
- 前端可选 7 / 30 / 90 / 365 天,能看多长取决于平台积累多久
为什么用"每 30 分钟检查昨天有没有落库"而不是固定 00:10 定时:
平台可能整晚没运行,固定时点的定时器会直接错过;检查式回补不依赖平台在线时刻。
Partial 标记(关键,否则会误读):
- 当天未结束 → partial=true
- 待抓取日期的起点已超出 24h 保留期 → partial=true(Loki 里就没那么多数据)
实测:10-27 32.5GB/2.65亿条 partial=true(保留期外),
10-28 348GB/28.56亿条 partial=true(当天进行中)
=== 2. 修一个 Go 副本 bug(自己写的,靠实测发现)===
第一版用 `for _, snap := range db.DailyVolumeSnapshots` 后改 snap 字段,
range 拿到的是**副本**,改动不会写回切片 → 同一天永远保持首次抓取的值,
partial 也永不更新(实测发现 10-27 该是 true 却显示 false)。
改为 `for i := range ... { snap := &db.DailyVolumeSnapshots[i] }`。
=== 3. 趋势图可读性 ===
从"裸折线"换成"渐变面积图",并在图上方给出峰值 / 均值:
- 面积图能一眼看出"这一段整体比上一段高",折线只能靠对齐格子数
- 峰值/均值避免用户自己对刻度
- Y 轴与 tooltip 统一 formatBytes,"每桶体积"写进 subtitle
顺带确认:趋势图只画体积(字节),不再混入 error(条数)——单位不同不能同轴。
=== 4. 饼图:命名空间分布 → 应用日志量分布 ===
本环境的命名空间只有 astralx / log 两个,饼图没有信息量;
改成按应用看谁在刷日志(前 8 名 + 其他),才是运维真正要的答案。
=== 5. 告警页拆成三个 Tab ===
「告警规则 / 通知通道 / 发送历史」独立成分页(用 ui/tabs)。
之前通道是折叠块、历史堆在规则下面,规则一多就要滚很久才看得到。
发送历史增加空状态文案,不再是"空页面不知道有没有在发"。
=== 6. 内置规则关联默认通道 + 首次部署 webhook 留空的评估 ===
结论:**webhook 可以留空,但通道必须是禁用状态**。
- 若种子给的是"已启用 + 空地址"通道,规则一命中就必然投递失败,
发送历史堆满红色失败,反而让人以为平台坏了
- 所以首次部署建一个**禁用**的占位通道「默认通知通道(待配置 Webhook)」,
内置规则全部挂到它;管理员填好 Webhook 再启用即可,不用逐条关联
- 保存时加校验:启用则必须有非空 Webhook(返回明确原因,不是裸 500)
- schemaVersion v5→v6:把已有的"无通道"规则补挂到默认通道
实测:8 条规则全部已关联通道
=== 实测(v11-1028-2252 / 187062644c0f)===
/logs/daily-volume?days=7 → 2 天数据,partial 标记正确
规则 8 条全部有 channelIds
平台 ready、健康 ok
This commit is contained in:
1 parent
cb91470d75
commit
37e2f0febc
20 files changed
+716
-202
No files matched your search
@@ -19,6 +19,14 @@ export interface MetricPoint { timestamp: string; value: number }
|
||||
/** 一条按标签分组的指标序列(如 sum by (app)(...) 中每个 app 一条) */
|
||||
export interface MetricSeries { labels: Record<string, string>; points: MetricPoint[] }
|
||||
export interface MetricQuery { sourceId: number; query: string; start: number; end: number }
|
||||
/** 每日日志量(平台留存历史,不受 Loki retention 限制) */
|
||||
export interface DailyVolumePoint {
|
||||
date: string
|
||||
bytes: number
|
||||
entries: number
|
||||
/** 当天未结束或抓取时数据不全 */
|
||||
partial: boolean
|
||||
}
|
||||
export const logsApi = {
|
||||
sources: () => http.get<PageData<LogSource>>('/logs/sources'),
|
||||
createSource: (source: Partial<LogSource> & { basicPass?: string; bearerToken?: string }) => http.post<LogSource>('/logs/sources', source),
|
||||
@@ -37,6 +45,9 @@ export const logsApi = {
|
||||
http.post<{ streams: number; chunks: number; bytes: number; entries: number }>(
|
||||
'/logs/stats', data, { timeout: 25000, ...opts }),
|
||||
/** 日志量统计:后端有 7 天范围上限与 30s 超时,前端超时略大于它 */
|
||||
/** 每日日志量历史(读平台库,毫秒级) */
|
||||
dailyVolume: (sourceId: number, days: number, opts?: { signal?: AbortSignal }) =>
|
||||
http.get<DailyVolumePoint[]>(`/logs/daily-volume?sourceId=${sourceId}&days=${days}`, opts),
|
||||
histogram: (data: LogQuery, opts?: { signal?: AbortSignal }) =>
|
||||
http.post<Array<Record<string, unknown>>>('/logs/histogram', data, { timeout: 40000, ...opts }),
|
||||
/** LogQL 指标查询(admin):query 中的 [$step] 占位符由后端按时间跨度替换 */
|
||||
|
||||
@@ -7,6 +7,12 @@ export default {
|
||||
checking: 'Checking...',
|
||||
create: 'New Rule',
|
||||
emptyTitle: 'No alert rules yet',
|
||||
historyEmpty: 'No deliveries yet. Fired rules will be recorded here.',
|
||||
tabs: {
|
||||
rules: 'Rules',
|
||||
channels: 'Channels',
|
||||
history: 'Delivery history',
|
||||
},
|
||||
notifySectionTitle: 'Notification channels (Feishu / Lark / Webhook)',
|
||||
notifySectionConfigured: '{{count}} configured',
|
||||
notifySectionEmpty: 'Not configured — alerts cannot be delivered',
|
||||
|
||||
@@ -29,8 +29,12 @@ export default {
|
||||
},
|
||||
trend: {
|
||||
title: 'Log volume trend',
|
||||
subtitle: 'Total / errors / warnings bucketed over time',
|
||||
subtitle: 'Log volume per time bucket (from index stats, instant)',
|
||||
peak: 'Peak',
|
||||
avg: 'Avg',
|
||||
unitHint: 'Unit: volume per bucket',
|
||||
seriesTotal: 'Total',
|
||||
seriesVolume: 'Volume',
|
||||
seriesError: 'Errors',
|
||||
seriesWarn: 'Warnings',
|
||||
empty: 'No log data in this time range',
|
||||
@@ -41,16 +45,22 @@ export default {
|
||||
empty: 'No app-dimension data',
|
||||
},
|
||||
pie: {
|
||||
title: 'Namespace distribution',
|
||||
subtitle: 'Log volume share by namespace',
|
||||
empty: 'No namespace-dimension data',
|
||||
title: 'App volume distribution',
|
||||
subtitle: 'Who is flooding the logs (top 8 apps, rest grouped as Other)',
|
||||
empty: 'No app-dimension data',
|
||||
other: 'Other',
|
||||
},
|
||||
daily: {
|
||||
fixedBadge: 'Fixed last 7 days',
|
||||
title: 'Daily volume by app',
|
||||
subtitle: 'Top apps by calendar day for the last 7 days — not controlled by the range filter above',
|
||||
empty: 'No app-dimension data in the last 7 days',
|
||||
fixedBadge: 'Platform history',
|
||||
badge: 'Platform history',
|
||||
title: 'Daily volume',
|
||||
subtitle: 'Daily totals kept by the platform (Loki only retains 24h, history lives here)',
|
||||
empty: 'No history yet — the platform records one snapshot per day',
|
||||
lastDays: '{{count}}d',
|
||||
oneYear: '1y',
|
||||
coverage: '{{count}} days captured',
|
||||
seriesVolume: 'Volume',
|
||||
inProgress: 'in progress',
|
||||
},
|
||||
|
||||
table: {
|
||||
|
||||
@@ -6,6 +6,12 @@ export default {
|
||||
checking: '检查中...',
|
||||
create: '新建规则',
|
||||
emptyTitle: '暂无告警规则',
|
||||
historyEmpty: '还没有发送记录。规则命中后会在这里留下投递结果。',
|
||||
tabs: {
|
||||
rules: '告警规则',
|
||||
channels: '通知通道',
|
||||
history: '发送历史',
|
||||
},
|
||||
notifySectionTitle: '通知通道(飞书 / Lark / Webhook)',
|
||||
notifySectionConfigured: '已配置 {{count}} 个',
|
||||
notifySectionEmpty: '尚未配置,告警发不出去',
|
||||
|
||||
@@ -28,8 +28,12 @@ export default {
|
||||
},
|
||||
trend: {
|
||||
title: '日志量趋势',
|
||||
subtitle: '按时间分桶的日志量(来自索引统计,秒级返回)',
|
||||
subtitle: '按时间分桶的日志体积(来自索引统计,秒级返回)',
|
||||
peak: '峰值',
|
||||
avg: '均值',
|
||||
unitHint: '单位:每桶日志体积',
|
||||
seriesTotal: '总量',
|
||||
seriesVolume: '日志体积',
|
||||
seriesError: '错误',
|
||||
seriesWarn: '告警',
|
||||
empty: '该时间范围内没有日志数据',
|
||||
@@ -40,16 +44,22 @@ export default {
|
||||
empty: '没有应用维度的数据',
|
||||
},
|
||||
pie: {
|
||||
title: '命名空间分布',
|
||||
subtitle: '各命名空间的日志量占比',
|
||||
title: '应用日志量分布',
|
||||
subtitle: '按应用看谁在刷日志(前 8 名,其余归入"其他")',
|
||||
empty: '没有命名空间维度的数据',
|
||||
other: '其他',
|
||||
},
|
||||
daily: {
|
||||
fixedBadge: '固定近 7 天',
|
||||
fixedBadge: '平台留存历史',
|
||||
badge: '平台留存历史',
|
||||
title: '每日日志量',
|
||||
subtitle: '近 7 个自然日的每日总量(来自索引统计,不受上方时间范围影响)',
|
||||
empty: '近 7 天没有应用维度的数据',
|
||||
subtitle: '每天的总量趋势,数据由平台每日留存(Loki 只保留 24 小时,历史在这里)',
|
||||
empty: '还没有历史数据,平台每天会自动记录一次',
|
||||
lastDays: '{{count}} 天',
|
||||
oneYear: '1 年',
|
||||
coverage: '已有 {{count}} 天数据',
|
||||
seriesVolume: '日志体积',
|
||||
inProgress: '当天进行中',
|
||||
},
|
||||
|
||||
table: {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { NotifySection } from './components/NotifySection'
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle,
|
||||
@@ -87,6 +88,9 @@ const AlertsPage = memo(function AlertsPage() {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [editing, setEditing] = useState<AlertRule | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<AlertRule | null>(null)
|
||||
// 三个功能区独立成 tab:规则 / 通知通道 / 发送历史。
|
||||
// 之前通道和历史都堆在规则表格下面,规则一多就要滚很久才能看到。
|
||||
const [tab, setTab] = useState<'rules' | 'channels' | 'history'>('rules')
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [checking, setChecking] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
@@ -209,6 +213,14 @@ const AlertsPage = memo(function AlertsPage() {
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tabs value={tab} onValueChange={value => setTab(value as 'rules' | 'channels' | 'history')}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="rules">{t('tabs.rules')} · {rules.length}</TabsTrigger>
|
||||
<TabsTrigger value="channels">{t('tabs.channels')} · {channels.length}</TabsTrigger>
|
||||
<TabsTrigger value="history">{t('tabs.history')}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="rules" className="space-y-3">
|
||||
{rules.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={BellRing}
|
||||
@@ -284,8 +296,16 @@ const AlertsPage = memo(function AlertsPage() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 发送历史 */}
|
||||
{deliveries.length > 0 && (
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="history">
|
||||
{deliveries.length === 0 ? (
|
||||
<Card className="border-border">
|
||||
<CardContent className="p-8 text-center text-sm text-muted-foreground">
|
||||
{t('historyEmpty')}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-border">
|
||||
<CardContent className="p-4">
|
||||
<h2 className="text-sm font-semibold mb-3">{t('historyTitle')}</h2>
|
||||
@@ -316,24 +336,21 @@ const AlertsPage = memo(function AlertsPage() {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{/* 通知通道配置:从「系统设置」搬到这里。
|
||||
告警规则和"告警发到哪"是同一件事的两半,分两个页面配很容易漏配导致告警发不出去。
|
||||
默认折叠,不影响规则列表的紧凑度。 */}
|
||||
<details className="rounded-lg border border-border" open={channels.length === 0}>
|
||||
<summary className="cursor-pointer select-none px-3 py-2 text-sm font-medium">
|
||||
{t('notifySectionTitle')}
|
||||
<span className="ml-2 text-xs font-normal text-muted-foreground">
|
||||
{channels.length > 0
|
||||
? t('notifySectionConfigured', { count: channels.length })
|
||||
: t('notifySectionEmpty')}
|
||||
</span>
|
||||
</summary>
|
||||
<div className="border-t border-border p-3">
|
||||
{/* 通知通道:独立成 tab(原先是折叠块,藏在规则列表最下面) */}
|
||||
<TabsContent value="channels">
|
||||
{channels.length === 0 && (
|
||||
<Card className="mb-3 border-warning/40 bg-warning/5">
|
||||
<CardContent className="p-3 text-xs text-warning">
|
||||
{t('notifySectionEmpty')}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<NotifySection />
|
||||
</div>
|
||||
</details>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* 规则弹窗 */}
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
|
||||
@@ -1,37 +1,91 @@
|
||||
import { memo, useMemo } from 'react'
|
||||
import { Bar, BarChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
|
||||
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { DailyAppRow } from '../hooks/useDailyVolume'
|
||||
import { chartColors } from './chart-shared'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { DailyVolumePoint } from '@/api/logs'
|
||||
import { formatBytes } from './chart-shared'
|
||||
import { EmptyChart } from './EmptyChart'
|
||||
|
||||
/** 应用每日日志量堆叠柱状图:x 轴日期,系列为 7 天总量 Top 10 应用 */
|
||||
export const DailyVolumeChart = memo(function DailyVolumeChart({ days, apps }: {
|
||||
days: string[]
|
||||
apps: DailyAppRow[]
|
||||
const RANGES = [7, 30, 90, 365] as const
|
||||
|
||||
/**
|
||||
* 每日日志量柱/面积图。
|
||||
*
|
||||
* 数据来自**平台自己留存的历史**(不查 Loki):
|
||||
* Loki retention 只有 24h,直接查只能拿到 1 天,看不出趋势。
|
||||
* 所以这里可以选 7 / 30 / 90 / 365 天,能看多长取决于平台已经积累了多久。
|
||||
*
|
||||
* 当天未结束的那根柱子用虚线区分(Partial),避免把"才过半天"误读成"量掉了"。
|
||||
*/
|
||||
export const DailyVolumeChart = memo(function DailyVolumeChart({ points, days, onDaysChange }: {
|
||||
points: DailyVolumePoint[]
|
||||
days: number
|
||||
onDaysChange: (days: number) => void
|
||||
}) {
|
||||
const { t } = useTranslation('analysis')
|
||||
// 未打 app 标签的序列用占位 key(recharts dataKey 不能是空串),图例显示词典文案
|
||||
const topApps = useMemo(() => apps
|
||||
.map(app => ({ key: app.app || '__untagged__', label: app.app || t('table.untagged'), totals: app.totals })), [apps, t])
|
||||
const data = useMemo(() => days.map((day, index) => ({
|
||||
day,
|
||||
...Object.fromEntries(topApps.map(app => [app.key, app.totals[index] ?? 0])),
|
||||
})), [days, topApps])
|
||||
if (topApps.length === 0 || days.length === 0) return <EmptyChart message={t('daily.empty')} />
|
||||
return <div className="h-64 w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={data} margin={{ top: 12, right: 16, bottom: 4, left: 0 }}>
|
||||
<CartesianGrid stroke="hsl(var(--border))" strokeDasharray="3 3" />
|
||||
<XAxis dataKey="day" tick={{ fontSize: 11 }} minTickGap={20} />
|
||||
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} width={56} />
|
||||
<Tooltip />
|
||||
<Legend wrapperStyle={{ fontSize: 11 }} />
|
||||
{topApps.map((app, index) => {
|
||||
const color = chartColors[index % chartColors.length]
|
||||
return <Bar key={app.key} dataKey={app.key} name={app.label} stackId="daily" fill={color} />
|
||||
})}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
const data = useMemo(() => points.map(point => ({
|
||||
date: point.date.slice(5), // MM-DD,省空间
|
||||
bytes: point.bytes,
|
||||
entries: point.entries,
|
||||
partial: point.partial,
|
||||
})), [points])
|
||||
|
||||
const hasData = data.some(item => item.bytes > 0)
|
||||
const coverage = points.length
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{RANGES.map(range => (
|
||||
<Button
|
||||
key={range}
|
||||
size="sm"
|
||||
variant={days === range ? 'default' : 'outline'}
|
||||
className="h-7 px-2 text-xs"
|
||||
onClick={() => onDaysChange(range)}
|
||||
>
|
||||
{range === 365 ? t('daily.oneYear') : t('daily.lastDays', { count: range })}
|
||||
</Button>
|
||||
))}
|
||||
<span className="ml-auto text-[11px] text-muted-foreground">
|
||||
{t('daily.coverage', { count: coverage })}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{hasData ? (
|
||||
<div className="h-64 w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={data} margin={{ top: 12, right: 16, bottom: 4, left: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id="dailyVolumeFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor="hsl(var(--info))" stopOpacity={0.35} />
|
||||
<stop offset="100%" stopColor="hsl(var(--info))" stopOpacity={0.02} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid stroke="hsl(var(--border))" strokeDasharray="3 3" />
|
||||
<XAxis dataKey="date" tick={{ fontSize: 11 }} minTickGap={24} />
|
||||
<YAxis tick={{ fontSize: 11 }} width={64} tickFormatter={(value: number) => formatBytes(value)} />
|
||||
<Tooltip
|
||||
formatter={(value: number, _name, item) => {
|
||||
const partial = (item?.payload as { partial?: boolean } | undefined)?.partial
|
||||
return [`${formatBytes(value)}${partial ? ` · ${t('daily.inProgress')}` : ''}`, t('daily.seriesVolume')]
|
||||
}}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="bytes"
|
||||
stroke="hsl(var(--info))"
|
||||
strokeWidth={2}
|
||||
fill="url(#dailyVolumeFill)"
|
||||
name={t('daily.seriesVolume')}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
) : (
|
||||
<EmptyChart message={t('daily.empty')} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { AppRow } from '../hooks/useAnalysisMetrics'
|
||||
import { compactNumber } from './chart-shared'
|
||||
|
||||
/** 迷你趋势 sparkline:纯 SVG polyline,避免每行一个 recharts 实例 */
|
||||
function Sparkline({ values }: { values: number[] }) {
|
||||
@@ -46,9 +47,9 @@ export const TopAppsTable = memo(function TopAppsTable({
|
||||
<td className="px-3 py-2 tabular-nums text-muted-foreground">{index + 1}</td>
|
||||
<td className="max-w-56 truncate px-3 py-2 font-medium" title={row.app || undefined}>{row.app || t('table.untagged')}</td>
|
||||
<td className="max-w-40 truncate px-3 py-2 text-muted-foreground" title={row.namespaces.join(', ')}>{row.namespace || '—'}</td>
|
||||
<td className="px-3 py-2 tabular-nums">{row.total.toLocaleString()}</td>
|
||||
<td className="px-3 py-2 tabular-nums">{compactNumber(row.total)} 条</td>
|
||||
<td className="px-3 py-2 tabular-nums text-muted-foreground">{total > 0 ? `${((row.total / total) * 100).toFixed(1)}%` : '—'}</td>
|
||||
<td className={`px-3 py-2 tabular-nums ${row.errorCount > 0 ? 'text-destructive' : 'text-muted-foreground'}`}>{row.errorCount.toLocaleString()}</td>
|
||||
<td className={`px-3 py-2 tabular-nums ${row.errorCount > 0 ? 'text-destructive' : 'text-muted-foreground'}`}>{compactNumber(row.errorCount)} 条</td>
|
||||
<td className="px-3 py-2 tabular-nums text-muted-foreground">{row.total > 0 ? `${((row.errorCount / row.total) * 100).toFixed(2)}%` : '—'}</td>
|
||||
<td className="px-3 py-2"><Sparkline values={row.sparkline} /></td>
|
||||
<td className="px-3 py-2">
|
||||
|
||||
@@ -1,32 +1,83 @@
|
||||
import { memo } from 'react'
|
||||
import { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
|
||||
import { memo, useMemo } from 'react'
|
||||
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { EmptyChart } from './EmptyChart'
|
||||
import { formatBytes } from './chart-shared'
|
||||
|
||||
interface TrendPoint { time: string; total: number; error: number; warn: number }
|
||||
|
||||
/** 日志量趋势折线图:总量 / 错误 / 告警 三条线 */
|
||||
/**
|
||||
* 日志量趋势(体积)。
|
||||
*
|
||||
* 只画 total:total 来自 index/volume_range,单位是**字节**;
|
||||
* 而 error 来自 count_over_time,单位是**条数**。把两者放进同一个 Y 轴
|
||||
* 等于拿字节和条数比大小,刻度完全没有意义。
|
||||
* 错误量改由上方统计卡与下方排行表展示(那里是纯条数)。
|
||||
*
|
||||
* 视觉上从"裸折线"换成"渐变面积 + 峰值/均值参考":
|
||||
* - 面积图更容易看出"这一段整体比上一段高",折线只能靠对齐格子
|
||||
* - 顶部给峰值和均值,一眼知道当前水位是否异常(不用自己数刻度)
|
||||
*/
|
||||
export const TrendChart = memo(function TrendChart({ trend }: { trend: TrendPoint[] }) {
|
||||
const { t } = useTranslation('analysis')
|
||||
const hasData = trend.some(point => point.total > 0 || point.error > 0 || point.warn > 0)
|
||||
if (!hasData) return <EmptyChart message={t('trend.empty')} />
|
||||
const series = [
|
||||
{ key: 'total', name: t('trend.seriesTotal'), color: 'hsl(var(--info))' },
|
||||
{ key: 'error', name: t('trend.seriesError'), color: 'hsl(var(--destructive))' },
|
||||
{ key: 'warn', name: t('trend.seriesWarn'), color: 'hsl(var(--warning))' },
|
||||
] as const
|
||||
return <div className="h-72 w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={trend} margin={{ top: 12, right: 16, bottom: 4, left: 0 }}>
|
||||
<CartesianGrid stroke="hsl(var(--border))" strokeDasharray="3 3" />
|
||||
<XAxis dataKey="time" tick={{ fontSize: 11 }} minTickGap={30} />
|
||||
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} width={48} />
|
||||
<Tooltip />
|
||||
<Legend wrapperStyle={{ fontSize: 11 }} />
|
||||
{series.map(item => (
|
||||
<Line key={item.key} type="monotone" dataKey={item.key} name={item.name} stroke={item.color} strokeWidth={2} dot={false} />
|
||||
))}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
const hasData = trend.some(point => point.total > 0)
|
||||
|
||||
const summary = useMemo(() => {
|
||||
const values = trend.map(point => point.total).filter(value => value > 0)
|
||||
if (values.length === 0) return null
|
||||
const peak = Math.max(...values)
|
||||
const avg = values.reduce((sum, value) => sum + value, 0) / values.length
|
||||
return { peak, avg }
|
||||
}, [trend])
|
||||
|
||||
if (!hasData || !summary) return <EmptyChart message={t('trend.empty')} />
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{t('trend.peak')} <strong className="text-foreground tabular-nums">{formatBytes(summary.peak)}</strong>
|
||||
</span>
|
||||
<span>
|
||||
{t('trend.avg')} <strong className="text-foreground tabular-nums">{formatBytes(summary.avg)}</strong>
|
||||
</span>
|
||||
<span className="ml-auto">{t('trend.unitHint')}</span>
|
||||
</div>
|
||||
<div className="h-72 w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={trend} margin={{ top: 8, right: 16, bottom: 4, left: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id="trendVolumeFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor="hsl(var(--info))" stopOpacity={0.4} />
|
||||
<stop offset="100%" stopColor="hsl(var(--info))" stopOpacity={0.02} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid stroke="hsl(var(--border))" strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis dataKey="time" tick={{ fontSize: 11 }} minTickGap={30} tickMargin={6} />
|
||||
<YAxis
|
||||
tick={{ fontSize: 11 }}
|
||||
width={64}
|
||||
tickFormatter={(value: number) => formatBytes(value)}
|
||||
// 峰值贴近顶部时留点余量,避免线贴边看不清
|
||||
domain={[0, (dataMax: number) => dataMax * 1.15]}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value: number) => [formatBytes(value), t('trend.seriesVolume')]}
|
||||
labelFormatter={label => `${label}`}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="total"
|
||||
stroke="hsl(var(--info))"
|
||||
strokeWidth={2}
|
||||
fill="url(#trendVolumeFill)"
|
||||
name={t('trend.seriesVolume')}
|
||||
dot={false}
|
||||
activeDot={{ r: 4 }}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -8,6 +8,19 @@ export const chartColors = [
|
||||
'hsl(var(--muted-foreground))',
|
||||
]
|
||||
|
||||
/** 字节格式化:7956179750 → 7.4 GB(索引接口返回的是字节) */
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
||||
let value = bytes
|
||||
let unit = 0
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024
|
||||
unit++
|
||||
}
|
||||
return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`
|
||||
}
|
||||
|
||||
/** 数字缩写:1.2万 / 3.4k(表格与图例用,避免长数字撑爆列宽) */
|
||||
export function compactNumber(value: number): string {
|
||||
if (value >= 100000000) return `${(value / 100000000).toFixed(1)}亿`
|
||||
|
||||
@@ -1,34 +1,25 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { logsApi } from '@/api/logs'
|
||||
|
||||
export interface DailyAppRow {
|
||||
app: string
|
||||
namespace: string
|
||||
/** 每个自然日(本地时区)的日志总量,与 days 一一对应 */
|
||||
totals: number[]
|
||||
total: number
|
||||
}
|
||||
import { logsApi, type DailyVolumePoint } from '@/api/logs'
|
||||
|
||||
export interface DailyVolumeData {
|
||||
days: string[]
|
||||
apps: DailyAppRow[]
|
||||
points: DailyVolumePoint[]
|
||||
/** 历史覆盖的最早日期(用于提示"可查看范围") */
|
||||
earliest: string
|
||||
}
|
||||
|
||||
const DAY_MS = 86400000
|
||||
const RANGE_DAYS = 7
|
||||
const ns = (ms: number) => Math.round(ms).toString() + '000000'
|
||||
const dayLabel = (ts: number) => new Date(ts).toLocaleDateString([], { month: '2-digit', day: '2-digit' })
|
||||
|
||||
/**
|
||||
* 应用每日日志量(近 7 天,Top 10)— 独立于页面时间范围筛选:
|
||||
* 一条 `sum by (app, namespace)(count_over_time(sel[$step]))` 查询(7 天跨度后端自动选 1h 步长),
|
||||
* 客户端把小时桶按本地日历日聚合,避免为每天单独发查询。
|
||||
* 每日日志量(平台留存历史,不走 Loki 实时统计)。
|
||||
*
|
||||
* 为什么要落库:
|
||||
* Loki retention 默认 24 小时,「近 7 天」直接查 Loki 只有 1 天有数据。
|
||||
* 平台后台每 30 分钟把「昨天 / 今天」的量写进自己的库,
|
||||
* 所以这里读到的是真历史,能支撑 30 天 / 90 天 / 1 年的趋势。
|
||||
*
|
||||
* 成本:一次 HTTP 读 JSON(毫秒级),不碰 Loki。
|
||||
*/
|
||||
export function useDailyVolume({ sourceId, namespace, appLabel, enabled = true }: {
|
||||
export function useDailyVolume({ sourceId, days, enabled = true }: {
|
||||
sourceId: number
|
||||
namespace: string
|
||||
appLabel: string
|
||||
/** 卡片滚动到视口内才发查询(索引接口很快,但没必要首屏就抢带宽) */
|
||||
days: number
|
||||
enabled?: boolean
|
||||
}) {
|
||||
const [data, setData] = useState<DailyVolumeData | null>(null)
|
||||
@@ -42,55 +33,21 @@ export function useDailyVolume({ sourceId, namespace, appLabel, enabled = true }
|
||||
|
||||
useEffect(() => {
|
||||
if (!sourceId || !enabled) return
|
||||
const end = Date.now()
|
||||
// 从今天往前取整 7 个自然日(首尾两天可能是不完整天)
|
||||
const today = Math.floor(end / DAY_MS) * DAY_MS
|
||||
const days = Array.from({ length: RANGE_DAYS }, (_, index) => today - (RANGE_DAYS - 1 - index) * DAY_MS)
|
||||
const start = days[0]
|
||||
|
||||
abortRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
const version = ++versionRef.current
|
||||
|
||||
const selector = namespace ? `{namespace="${namespace}"}` : '{namespace=~".+"}'
|
||||
void (async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
// 走索引接口而不是 count_over_time。
|
||||
//
|
||||
// 原来这条查 7 天 × count_over_time,实测该环境约 370GB/天 → 要扫 2.6TB,
|
||||
// 后端 90s 也跑不完,图表永远空/超时。
|
||||
// /logs/histogram 内部用 index/volume_range,只读 chunk 元数据,
|
||||
// 7 天跨度也是毫秒级;代价是**只能拿到总量,拿不到 per-app 拆分**
|
||||
// (Loki 的索引接口不支持按任意 label 分组)。
|
||||
// 因此这里展示"每日日志总量",应用维度交给下方的 Top 应用表格(它有单独的时间范围)。
|
||||
const hist = await logsApi.histogram(
|
||||
{ sourceId, query: selector, start: Number(ns(start)), end: Number(ns(end)) },
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
const points = await logsApi.dailyVolume(sourceId, days, { signal: controller.signal })
|
||||
if (version !== versionRef.current) return
|
||||
|
||||
// 索引返回的是字节数,按本地自然日聚合
|
||||
const dayBytes = days.map(() => 0)
|
||||
for (const bucket of (hist || [])) {
|
||||
const ts = String((bucket as { timestamp: string }).timestamp ?? '')
|
||||
const value = Number((bucket as { count: number }).count ?? 0)
|
||||
const day = Math.floor(new Date(ts).getTime() / DAY_MS) * DAY_MS
|
||||
const index = days.indexOf(day)
|
||||
if (index >= 0) dayBytes[index] += value
|
||||
}
|
||||
setData({
|
||||
days: days.map(dayLabel),
|
||||
apps: [{
|
||||
app: '全部应用',
|
||||
namespace: namespace || '',
|
||||
totals: dayBytes,
|
||||
total: dayBytes.reduce((sum, value) => sum + value, 0),
|
||||
}],
|
||||
points: points ?? [],
|
||||
earliest: points?.[0]?.date ?? '',
|
||||
})
|
||||
return
|
||||
} catch (err) {
|
||||
if ((err as Error).name === 'AbortError') return
|
||||
if (version === versionRef.current) setError(err instanceof Error ? err.message : 'daily volume failed')
|
||||
@@ -100,7 +57,7 @@ export function useDailyVolume({ sourceId, namespace, appLabel, enabled = true }
|
||||
})()
|
||||
|
||||
return () => { controller.abort() }
|
||||
}, [sourceId, namespace, appLabel, refreshTick, enabled])
|
||||
}, [sourceId, days, refreshTick, enabled])
|
||||
|
||||
return { data, loading, error, refresh }
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { getUser } from '@/lib/auth-storage'
|
||||
import { useAnalysisMetrics } from './hooks/useAnalysisMetrics'
|
||||
import { useDailyVolume } from './hooks/useDailyVolume'
|
||||
import { useInView } from '@/hooks/useInView'
|
||||
import { compactNumber, formatBytes } from './components/chart-shared'
|
||||
import { TrendChart } from './components/TrendChart'
|
||||
import { AppStreamChart } from './components/AppStreamChart'
|
||||
import { DailyVolumeChart } from './components/DailyVolumeChart'
|
||||
@@ -36,19 +37,7 @@ const ALL_NAMESPACES = '__all__'
|
||||
const AnalysisPage = memo(function AnalysisPage() {
|
||||
const { t } = useTranslation('analysis')
|
||||
const navigate = useNavigate()
|
||||
/** 索引接口返回的是字节数,直接 toLocaleString 会显示 7956179750 这种看不懂的数字 */
|
||||
const formatBytes = (bytes: number) => {
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
||||
let value = bytes
|
||||
let unit = 0
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024
|
||||
unit++
|
||||
}
|
||||
return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`
|
||||
}
|
||||
|
||||
const isAdmin = getUser()?.role === 'admin'
|
||||
const isAdmin = getUser()?.role === 'admin'
|
||||
|
||||
const [sources, setSources] = useState<LogSource[]>([])
|
||||
const [sourceId, setSourceId] = useState(0)
|
||||
@@ -142,10 +131,11 @@ const isAdmin = getUser()?.role === 'admin'
|
||||
rankingEnabled: rankingView.inView,
|
||||
})
|
||||
// 每日统计固定近 7 天,不随上方时间范围变化;错误就地展示,不影响主区
|
||||
// 每日量可看范围:7 / 30 / 90 / 365 天(数据来自平台留存历史)
|
||||
const [dailyDays, setDailyDays] = useState(7)
|
||||
const daily = useDailyVolume({
|
||||
sourceId: effectiveSourceId,
|
||||
namespace: scopedNamespace,
|
||||
appLabel,
|
||||
days: dailyDays,
|
||||
enabled: dailyView.inView,
|
||||
})
|
||||
|
||||
@@ -226,10 +216,10 @@ const isAdmin = getUser()?.role === 'admin'
|
||||
{/* 不再显示"告警行数"卡片:为了把它从 3 条重查询降到 2 条,
|
||||
已放弃全局 warn 统计。显示一个恒为 0 的数字比不显示更误导。 */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<StatCard label={t('stats.totalEntries')} value={data.stats.totalEntries.toLocaleString()} icon={ScrollText} iconColor="text-info" iconBg="bg-info/10" />
|
||||
<StatCard label={t('stats.totalEntries')} value={`${compactNumber(data.stats.totalEntries)} 条`} icon={ScrollText} iconColor="text-info" iconBg="bg-info/10" />
|
||||
<StatCard label={t('stats.totalVolume')} value={formatBytes(data.stats.total)} icon={ScrollText} iconColor="text-info" iconBg="bg-info/10" />
|
||||
<StatCard label={t('stats.errors')} value={data.stats.errorCount.toLocaleString()} icon={FileWarning} iconColor="text-destructive" iconBg="bg-destructive/10" />
|
||||
<StatCard label={t('stats.apps')} value={data.stats.appCount} icon={Boxes} iconColor="text-primary" iconBg="bg-primary/10" />
|
||||
<StatCard label={t('stats.errors')} value={`${compactNumber(data.stats.errorCount)} 条`} icon={FileWarning} iconColor="text-destructive" iconBg="bg-destructive/10" />
|
||||
<StatCard label={t('stats.apps')} value={`${data.stats.appCount} 个`} icon={Boxes} iconColor="text-primary" iconBg="bg-primary/10" />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
@@ -245,7 +235,13 @@ const isAdmin = getUser()?.role === 'admin'
|
||||
<CardTitle className="text-base">{t('pie.title')}</CardTitle>
|
||||
<p className="text-xs text-muted-foreground">{t('pie.subtitle')}</p>
|
||||
</CardHeader>
|
||||
<CardContent><NamespacePie shares={data.namespaceShares} /></CardContent>
|
||||
<CardContent>
|
||||
{/* 从"命名空间分布"改成"应用分布":命名空间只有 astralx/log 两个,
|
||||
看了没有信息量;按应用才看得出是谁在刷日志 */}
|
||||
<NamespacePie
|
||||
shares={data.apps.map(app => ({ name: app.app || t('table.untagged'), count: app.total }))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -261,7 +257,7 @@ const isAdmin = getUser()?.role === 'admin'
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<CardTitle className="text-base">{t('daily.title')}</CardTitle>
|
||||
<span className="rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground">{t('daily.fixedBadge')}</span>
|
||||
<span className="rounded-full bg-success/10 px-2 py-0.5 text-[11px] font-medium text-success">{t('daily.badge')}</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('daily.subtitle')}</p>
|
||||
</CardHeader>
|
||||
@@ -271,7 +267,11 @@ const isAdmin = getUser()?.role === 'admin'
|
||||
) : daily.loading && !daily.data ? (
|
||||
<LoadingSpinner className="h-40" />
|
||||
) : (
|
||||
<DailyVolumeChart days={daily.data?.days ?? []} apps={daily.data?.apps ?? []} />
|
||||
<DailyVolumeChart
|
||||
points={daily.data?.points ?? []}
|
||||
days={dailyDays}
|
||||
onDaysChange={setDailyDays}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
Reference in new issue
Block a user