Skip to content

Modern Docker Management, Designed for Everyone

feat: updated log viewer inspired by dozzle (#2146)

Kyle Mendell4743b8ff3df0
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 03310aefc..069ef39f7 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -16,6 +16,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/models"
dockerutils "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/containerstats"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/timeouts"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
containertypes "github.com/getarcaneapp/arcane/types/container"
@@ -33,6 +34,7 @@ type ContainerService struct {
eventService *EventService
imageService *ImageService
settingsService *SettingsService
+ statsHistory containerstats.Store
}
const (
@@ -578,13 +580,14 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,
defer func() { _ = stats.Body.Close() }()
decoder := json.NewDecoder(stats.Body)
+ historySent := false
for {
if err := ctx.Err(); err != nil {
return err
}
- var statsData any
+ var statsData container.StatsResponse
if err := decoder.Decode(&statsData); err != nil {
if ctx.Err() != nil {
return ctx.Err()
@@ -595,8 +598,25 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,
return fmt.Errorf("failed to decode stats: %w", err)
}
+ recordedAt := statsData.Read
+ if recordedAt.IsZero() {
+ recordedAt = time.Now()
+ }
+
+ payload := containertypes.StatsStreamPayload{
+ StatsResponse: statsData,
+ CurrentHistorySample: containerstats.BuildSample(statsData),
+ }
+ payload.StatsHistory = s.statsHistory.Record(
+ containerID,
+ payload.CurrentHistorySample,
+ !historySent,
+ recordedAt,
+ )
+ historySent = true
+
select {
- case statsChan <- statsData:
+ case statsChan <- payload:
case <-ctx.Done():
return ctx.Err()
}
diff --git a/backend/pkg/libarcane/containerstats/history.go b/backend/pkg/libarcane/containerstats/history.go
new file mode 100644
index 000000000..ec4032fa8
--- /dev/null
+++ b/backend/pkg/libarcane/containerstats/history.go
@@ -0,0 +1,142 @@
+package containerstats
+
+import (
+ "math"
+ "sync"
+ "time"
+
+ containertypes "github.com/getarcaneapp/arcane/types/container"
+ dockercontainer "github.com/moby/moby/api/types/container"
+)
+
+const (
+ HistoryCapacity = 30
+ historyTTL = 10 * time.Minute
+ historyPruneInterval = time.Minute
+)
+
+type Store struct {
+ mu sync.Mutex
+ histories map[string]*historyBuffer
+ lastPrune time.Time
+}
+
+type historyBuffer struct {
+ samples [HistoryCapacity]containertypes.StatsHistorySample
+ start int
+ count int
+ updatedAt time.Time
+}
+
+func BuildSample(stats dockercontainer.StatsResponse) containertypes.StatsHistorySample {
+ memoryUsage := calculateMemoryUsageInternal(stats)
+ return containertypes.StatsHistorySample{
+ CPUTenths: percentToTenthsInternal(calculateCPUPercentInternal(stats)),
+ MemoryTenths: percentToTenthsInternal(calculateMemoryPercentInternal(stats)),
+ MemoryUsageBytes: memoryUsage,
+ }
+}
+
+func (s *Store) Record(containerID string, sample containertypes.StatsHistorySample, includeHistory bool, recordedAt time.Time) []containertypes.StatsHistorySample {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.histories == nil {
+ s.histories = make(map[string]*historyBuffer)
+ }
+
+ s.maybePruneLockedInternal(recordedAt)
+
+ buffer := s.histories[containerID]
+ if buffer == nil {
+ buffer = &historyBuffer{}
+ s.histories[containerID] = buffer
+ }
+
+ buffer.append(sample, recordedAt)
+
+ if !includeHistory {
+ return nil
+ }
+
+ return buffer.snapshot()
+}
+
+func (b *historyBuffer) append(sample containertypes.StatsHistorySample, recordedAt time.Time) {
+ if b.count < HistoryCapacity {
+ index := (b.start + b.count) % HistoryCapacity
+ b.samples[index] = sample
+ b.count++
+ } else {
+ b.samples[b.start] = sample
+ b.start = (b.start + 1) % HistoryCapacity
+ }
+
+ b.updatedAt = recordedAt
+}
+
+func (b *historyBuffer) snapshot() []containertypes.StatsHistorySample {
+ if b.count == 0 {
+ return nil
+ }
+
+ out := make([]containertypes.StatsHistorySample, 0, b.count)
+ for i := range b.count {
+ index := (b.start + i) % HistoryCapacity
+ out = append(out, b.samples[index])
+ }
+ return out
+}
+
+func (s *Store) maybePruneLockedInternal(now time.Time) {
+ if now.IsZero() {
+ now = time.Now()
+ }
+
+ if !s.lastPrune.IsZero() && now.Sub(s.lastPrune) < historyPruneInterval {
+ return
+ }
+
+ s.lastPrune = now
+ for containerID, buffer := range s.histories {
+ if buffer == nil || now.Sub(buffer.updatedAt) > historyTTL {
+ delete(s.histories, containerID)
+ }
+ }
+}
+
+func calculateCPUPercentInternal(stats dockercontainer.StatsResponse) float64 {
+ cpuDelta := float64(stats.CPUStats.CPUUsage.TotalUsage) - float64(stats.PreCPUStats.CPUUsage.TotalUsage)
+ systemDelta := float64(stats.CPUStats.SystemUsage) - float64(stats.PreCPUStats.SystemUsage)
+
+ if systemDelta <= 0 || cpuDelta <= 0 {
+ return 0
+ }
+
+ return math.Min(math.Max((cpuDelta/systemDelta)*100, 0), 100)
+}
+
+func calculateMemoryPercentInternal(stats dockercontainer.StatsResponse) float64 {
+ limit := stats.MemoryStats.Limit
+ if limit == 0 {
+ return 0
+ }
+
+ usage := calculateMemoryUsageInternal(stats)
+ return math.Min(math.Max((float64(usage)/float64(limit))*100, 0), 100)
+}
+
+func calculateMemoryUsageInternal(stats dockercontainer.StatsResponse) uint64 {
+ usage := stats.MemoryStats.Usage
+ inactiveFile := stats.MemoryStats.Stats["inactive_file"]
+ if usage <= inactiveFile {
+ return 0
+ }
+
+ return usage - inactiveFile
+}
+
+func percentToTenthsInternal(value float64) uint16 {
+ clamped := math.Min(math.Max(value, 0), 100)
+ return uint16(math.Round(clamped * 10))
+}
diff --git a/backend/pkg/libarcane/containerstats/history_test.go b/backend/pkg/libarcane/containerstats/history_test.go
new file mode 100644
index 000000000..c8c61ada1
--- /dev/null
+++ b/backend/pkg/libarcane/containerstats/history_test.go
@@ -0,0 +1,102 @@
+package containerstats
+
+import (
+ "testing"
+ "time"
+
+ containertypes "github.com/getarcaneapp/arcane/types/container"
+ "github.com/moby/moby/api/types/container"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildSample(t *testing.T) {
+ stats := container.StatsResponse{
+ CPUStats: container.CPUStats{
+ CPUUsage: container.CPUUsage{TotalUsage: 250},
+ SystemUsage: 500,
+ },
+ PreCPUStats: container.CPUStats{
+ CPUUsage: container.CPUUsage{TotalUsage: 50},
+ SystemUsage: 100,
+ },
+ MemoryStats: container.MemoryStats{
+ Usage: 700,
+ Limit: 1000,
+ Stats: map[string]uint64{"inactive_file": 100},
+ },
+ }
+
+ sample := BuildSample(stats)
+
+ require.Equal(t, uint16(500), sample.CPUTenths)
+ require.Equal(t, uint16(600), sample.MemoryTenths)
+ require.Equal(t, uint64(600), sample.MemoryUsageBytes)
+}
+
+func TestStoreRecordCapsAndPreservesOrder(t *testing.T) {
+ var store Store
+ baseTime := time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC)
+
+ for i := 0; i < HistoryCapacity+5; i++ {
+ store.Record(
+ "container-1",
+ containertypes.StatsHistorySample{
+ CPUTenths: uint16(i),
+ MemoryTenths: uint16(i + 100),
+ MemoryUsageBytes: uint64(i + 1000),
+ },
+ false,
+ baseTime.Add(time.Duration(i)*time.Second),
+ )
+ }
+
+ snapshot := snapshotForTest(&store, "container-1", baseTime.Add(5*time.Minute))
+ require.Len(t, snapshot, HistoryCapacity)
+
+ for i, sample := range snapshot {
+ expected := i + 5
+ require.Equal(t, uint16(expected), sample.CPUTenths)
+ require.Equal(t, uint16(expected+100), sample.MemoryTenths)
+ require.Equal(t, uint64(expected+1000), sample.MemoryUsageBytes)
+ }
+}
+
+func TestStoreRecordPrunesExpiredContainers(t *testing.T) {
+ var store Store
+ baseTime := time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC)
+
+ store.Record("stale-container", containertypes.StatsHistorySample{CPUTenths: 111, MemoryTenths: 222, MemoryUsageBytes: 333}, false, baseTime)
+ store.Record(
+ "fresh-container",
+ containertypes.StatsHistorySample{CPUTenths: 333, MemoryTenths: 444, MemoryUsageBytes: 555},
+ false,
+ baseTime.Add(historyTTL-historyPruneInterval),
+ )
+
+ staleSnapshot := snapshotForTest(&store, "stale-container", baseTime.Add(historyTTL+time.Minute))
+ freshSnapshot := snapshotForTest(
+ &store,
+ "fresh-container",
+ baseTime.Add(historyTTL-historyPruneInterval+time.Minute),
+ )
+
+ require.Nil(t, staleSnapshot)
+ require.Len(t, freshSnapshot, 1)
+ require.Equal(t, uint16(333), freshSnapshot[0].CPUTenths)
+ require.Equal(t, uint16(444), freshSnapshot[0].MemoryTenths)
+ require.Equal(t, uint64(555), freshSnapshot[0].MemoryUsageBytes)
+}
+
+func snapshotForTest(store *Store, containerID string, now time.Time) []containertypes.StatsHistorySample {
+ store.mu.Lock()
+ defer store.mu.Unlock()
+
+ store.maybePruneLockedInternal(now)
+
+ buffer := store.histories[containerID]
+ if buffer == nil {
+ return nil
+ }
+
+ return buffer.snapshot()
+}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index db2cc81ba..cc9ca3cd2 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -171,7 +171,7 @@
"common_loading_label": "Loading - {label}",
"common_create": "Create",
"common_logs": "Logs",
- "common_json": "JSON",
+ "common_parsed": "Parsed",
"common_raw": "Raw",
"common_select_locale": "Select locale",
"common_show": "Show",
@@ -180,6 +180,9 @@
"common_token_placeholder": "Your access token",
"common_keep_placeholder": "Leave empty to keep current",
"common_toggle_theme": "Toggle theme",
+ "log_auto_scroll_tooltip": "Keeps the view pinned to the newest log lines while new entries arrive.",
+ "log_auto_start_tooltip": "Starts streaming logs automatically when you open this panel.",
+ "log_parsed_mode_tooltip": "Shows structured logs in parsed form when available. Turn it off to see the original raw line text.",
"common_logout": "Logout",
"common_redeploy": "Redeploy",
"common_use_template": "Use Template",
diff --git a/frontend/src/lib/components/arcane-button/variants.ts b/frontend/src/lib/components/arcane-button/variants.ts
index 6a2c25009..5a183ef7e 100644
--- a/frontend/src/lib/components/arcane-button/variants.ts
+++ b/frontend/src/lib/components/arcane-button/variants.ts
@@ -205,7 +205,7 @@ export const actionConfigs = {
loadingLabel: m.common_action_fetching_logs()
},
json: {
- defaultLabel: m.common_json(),
+ defaultLabel: m.common_parsed(),
IconComponent: CodeIcon,
tone: 'outline',
loadingLabel: m.common_processing()
diff --git a/frontend/src/lib/components/code-editor/theme.ts b/frontend/src/lib/components/code-editor/theme.ts
index ac9d768f0..ed1fbfea3 100644
--- a/frontend/src/lib/components/code-editor/theme.ts
+++ b/frontend/src/lib/components/code-editor/theme.ts
@@ -141,4 +141,3 @@ export const arcaneLightInit = (options?: Partial<CreateThemeOptions>) => {
styles: [...dynamicStyles, ...styles]
});
};
-
diff --git a/frontend/src/lib/components/logs/log-controls.svelte b/frontend/src/lib/components/logs/log-controls.svelte
index 501147b38..f325f3ade 100644
--- a/frontend/src/lib/components/logs/log-controls.svelte
+++ b/frontend/src/lib/components/logs/log-controls.svelte
@@ -1,5 +1,7 @@
<script lang="ts">
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
import * as Select from '$lib/components/ui/select';
import { m } from '$lib/paraglide/messages';
import { PersistedState } from 'runed';
@@ -13,7 +15,6 @@
disabled = false,
onStart,
onStop,
- onClear,
onRefresh
}: {
autoScroll: boolean;
@@ -24,7 +25,6 @@
disabled?: boolean;
onStart?: () => void;
onStop?: () => void;
- onClear?: () => void;
onRefresh?: () => void;
} = $props();
@@ -39,7 +39,7 @@
const persistedTailLines = new PersistedState('arcane_log_tail_lines', '100');
const persistedAutoStart = new PersistedState('arcane_log_auto_start', 'false');
- const persistedJsonParsing = new PersistedState('arcane_log_json_parsing', 'false');
+ const persistedJsonParsing = new PersistedState('arcane_log_json_parsing_v3', 'false');
let selectedTail = $state<string>(persistedTailLines.current || (tailLines >= 999999 ? 'all' : String(tailLines)));
@@ -71,16 +71,56 @@
const selectedLabel = $derived(tailOptions.find((o) => o.value === selectedTail)?.label ?? m.log_tail_100_lines());
</script>
-<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
- <label class="flex items-center gap-2">
- <input type="checkbox" bind:checked={autoScroll} class="size-4" />
- <span class="text-sm font-medium">{m.common_autoscroll()}</span>
- </label>
+<div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-end">
+ <div class="flex flex-wrap items-center gap-4">
+ <ArcaneTooltip.Root>
+ <ArcaneTooltip.Trigger>
+ <SwitchWithLabel
+ id="auto-scroll-toggle"
+ checked={autoScroll}
+ label={m.common_autoscroll()}
+ onCheckedChange={(checked) => {
+ autoScroll = checked;
+ }}
+ />
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content side="bottom" class="max-w-xs">
+ {m.log_auto_scroll_tooltip()}
+ </ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
- <label class="flex items-center gap-2">
- <input type="checkbox" bind:checked={autoStartLogs} class="size-4" />
- <span class="text-sm font-medium">{m.auto_start()}</span>
- </label>
+ <ArcaneTooltip.Root>
+ <ArcaneTooltip.Trigger>
+ <SwitchWithLabel
+ id="auto-start-logs-toggle"
+ checked={autoStartLogs}
+ label={m.auto_start()}
+ onCheckedChange={(checked) => {
+ autoStartLogs = checked;
+ }}
+ />
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content side="bottom" class="max-w-xs">
+ {m.log_auto_start_tooltip()}
+ </ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
+
+ <ArcaneTooltip.Root>
+ <ArcaneTooltip.Trigger>
+ <SwitchWithLabel
+ id="parsed-log-mode-toggle"
+ checked={showParsedJson}
+ label={showParsedJson ? m.common_parsed() : m.common_raw()}
+ onCheckedChange={(checked) => {
+ showParsedJson = checked;
+ }}
+ />
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content side="bottom" class="max-w-xs">
+ {m.log_parsed_mode_tooltip()}
+ </ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
+ </div>
<Select.Root type="single" bind:value={selectedTail} disabled={isStreaming} onValueChange={(v: string) => (selectedTail = v)}>
<Select.Trigger class="h-9 w-32 text-xs">
@@ -93,15 +133,7 @@
</Select.Content>
</Select.Root>
- <div class="flex items-center gap-2">
- <ArcaneButton
- action="base"
- tone="outline"
- size="sm"
- class="text-xs font-medium"
- onclick={onClear}
- customLabel={m.common_clear()}
- />
+ <div class="flex items-center gap-3">
{#if isStreaming}
<ArcaneButton action="stop" tone="outline" size="sm" class="text-xs font-medium" onclick={onStop} />
{:else}
@@ -111,19 +143,10 @@
action="refresh"
tone="outline"
size="sm"
- class="px-2"
+ class="text-xs font-medium"
onclick={onRefresh}
aria-label={m.log_refresh_aria_label()}
title={m.common_refresh()}
- showLabel={false}
- />
- <ArcaneButton
- action="json"
- tone={showParsedJson ? 'outline-primary' : 'outline'}
- size="sm"
- class="text-xs font-medium"
- customLabel={showParsedJson ? m.common_raw() : m.common_json()}
- onclick={() => (showParsedJson = !showParsedJson)}
/>
</div>
</div>
diff --git a/frontend/src/lib/components/logs/log-viewer.svelte b/frontend/src/lib/components/logs/log-viewer.svelte
index 1716815ac..0e4daf93d 100644
--- a/frontend/src/lib/components/logs/log-viewer.svelte
+++ b/frontend/src/lib/components/logs/log-viewer.svelte
@@ -1,25 +1,23 @@
<script lang="ts">
+ // Dozzle reference: the grouped row shell and left-side timestamp treatment here were
+ // informed by amir20/dozzle's LogItem.vue and GroupedLogItem.vue.
import { dev } from '$app/environment';
+ import * as Collapsible from '$lib/components/ui/collapsible';
+ import { ArrowDownIcon, ArrowRightIcon } from '$lib/icons';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { m } from '$lib/paraglide/messages';
import { ReconnectingWebSocket } from '$lib/utils/ws';
import { cn } from '$lib/utils';
import { ansiToHtml } from '$lib/utils/ansi';
- import { stripAnsi } from '$lib/utils/log-text';
import { onDestroy } from 'svelte';
+ import {
+ buildLogDisplayEntries,
+ tryParseStructuredLog,
+ type LogViewerDisplayEntry,
+ type LogViewerEntry
+ } from './log-viewer.utils';
import StructuredLogEntry from './structured-log-entry.svelte';
- interface LogEntry {
- id: number;
- timestamp: string;
- level: 'stdout' | 'stderr' | 'info' | 'error';
- message: string;
- service?: string;
- containerId?: string;
- parsedJson?: any;
- isJson?: boolean;
- }
-
interface Props {
class?: string;
containerId?: string | null;
@@ -30,11 +28,11 @@
showTimestamps?: boolean;
height?: string;
tailLines?: number;
- onClear?: () => void;
onToggleAutoScroll?: () => void;
onStart?: () => void;
onStop?: () => void;
showParsedJson?: boolean;
+ groupAdjacentLines?: boolean;
}
let {
@@ -47,15 +45,15 @@
showTimestamps = false,
height = '400px',
tailLines = 100,
- onClear,
onToggleAutoScroll,
onStart,
onStop,
- showParsedJson = $bindable(false)
+ showParsedJson = $bindable(false),
+ groupAdjacentLines = false
}: Props = $props();
- let logs: LogEntry[] = $state([]);
- let pending: LogEntry[] = [];
+ let logs: LogViewerEntry[] = $state([]);
+ let pending: LogViewerEntry[] = [];
let flushScheduled = false;
let seq = 0;
@@ -69,6 +67,15 @@
return logs.filter((l) => l.id >= dropBefore);
});
+ let displayLogs = $derived.by(() =>
+ buildLogDisplayEntries(visibleLogs, {
+ groupAdjacentLines,
+ type
+ })
+ );
+ let expandedGroups = $state<Set<number>>(new Set());
+ let hasAutoEnabledStructuredView = $state(false);
+
function maybeCompact() {
const threshold = maxLines * COMPACT_FACTOR;
if (logs.length <= threshold) return;
@@ -105,21 +112,25 @@
});
}
+ function resetLogState() {
+ logs = [];
+ pending = [];
+ seq = 0;
+ dropBefore = 0;
+ lastCompactSeq = 0;
+ expandedGroups = new Set();
+ hasAutoEnabledStructuredView = false;
+ }
+
export async function clearLogs(opts?: { hard?: boolean; restart?: boolean }) {
const hard = opts?.hard === true;
if (hard) {
- logs = [];
- pending = [];
- seq = 0;
- dropBefore = 0;
- lastCompactSeq = 0;
+ resetLogState();
} else {
dropBefore = seq;
}
- onClear?.();
-
if (opts?.restart) {
await stopLogStream();
startLogStream();
@@ -146,6 +157,9 @@
const humanType = $derived(type === 'project' ? m.project() : m.container());
const selectedTargetId = $derived(type === 'project' ? projectId : containerId);
+ const fillParent = $derived(height === '100%');
+ const minHeight = $derived(height === '100%' ? '0' : '300px');
+ const viewportStyle = $derived(fillParent ? 'min-height: 0;' : `height: ${height}; min-height: ${minHeight};`);
function buildWebSocketEndpoint(path: string): string {
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
@@ -176,6 +190,10 @@
return;
}
+ // A manual stop/start should reload the backend tail instead of appending
+ // onto the previous in-memory session buffer.
+ resetLogState();
+
connecting = true;
const sessionId = ++streamSession;
currentStreamSession = sessionId;
@@ -295,16 +313,22 @@
function addLogEntry(logData: { level: string; message: string; timestamp?: string; service?: string; containerId?: string }) {
const timestamp = logData.timestamp || new Date().toISOString();
- const { isJson, parsed } = tryParseJson(logData.message);
+ const { isJson, isStructured, parsed } = tryParseStructuredLog(logData.message);
+
+ if (isStructured && !hasAutoEnabledStructuredView && !showParsedJson) {
+ hasAutoEnabledStructuredView = true;
+ showParsedJson = true;
+ }
pending.push({
id: seq++,
timestamp,
- level: logData.level as LogEntry['level'],
+ level: logData.level as LogViewerEntry['level'],
message: logData.message,
service: logData.service,
- containerId: logData.containerId,
+ containerId: logData.containerId ?? (type === 'container' ? (containerId ?? undefined) : undefined),
isJson,
+ isStructured,
parsedJson: parsed
});
scheduleFlush();
@@ -327,7 +351,7 @@
return logs.length;
}
- function getLevelClass(level: LogEntry['level']): string {
+ function getLevelClass(level: LogViewerEntry['level']): string {
switch (level) {
case 'stderr':
case 'error':
@@ -365,17 +389,8 @@
return colors[Math.abs(hash) % colors.length] ?? 'text-gray-300';
}
- function tryParseJson(message: string): { isJson: boolean; parsed?: any } {
- const trimmed = stripAnsi(message).trim();
- if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
- return { isJson: false };
- }
- try {
- const parsed = JSON.parse(trimmed);
- return { isJson: true, parsed };
- } catch {
- return { isJson: false };
- }
+ function isStructuredLogData(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
}
$effect(() => {
@@ -397,21 +412,105 @@
(async () => {
await stopLogStream(false);
logs = [];
+ hasAutoEnabledStructuredView = false;
if (currentStreamKey === key) {
startLogStream();
}
})();
} else {
logs = [];
+ hasAutoEnabledStructuredView = false;
}
} else if (!currentStreamKey) {
// First time - just set the key, don't auto-start
currentStreamKey = key;
}
});
+
+ function getDisplayEntryLevel(displayEntry: LogViewerDisplayEntry): LogViewerEntry['level'] {
+ return displayEntry.entries[0]?.level ?? 'stdout';
+ }
+
+ function getDisplayEntryService(displayEntry: LogViewerDisplayEntry): string | undefined {
+ return displayEntry.entries[0]?.service;
+ }
+
+ function getDisplayEntryTimestamp(displayEntry: LogViewerDisplayEntry): string | undefined {
+ return displayEntry.entries[0]?.timestamp;
+ }
+
+ const logTimestampFormatter = new Intl.DateTimeFormat('en-US', {
+ month: '2-digit',
+ day: '2-digit',
+ year: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hour12: true
+ });
+
+ function formatLogTimestamp(timestamp: string | undefined): string {
+ if (!timestamp) return '';
+ const parsedTimestamp = new Date(timestamp);
+ if (Number.isNaN(parsedTimestamp.getTime())) {
+ return timestamp;
+ }
+ return logTimestampFormatter.format(parsedTimestamp);
+ }
+
+ function isGroupExpanded(displayEntry: LogViewerDisplayEntry): boolean {
+ return expandedGroups.has(displayEntry.id);
+ }
+
+ function setGroupExpanded(displayEntry: LogViewerDisplayEntry, open: boolean) {
+ const next = new Set(expandedGroups);
+ if (open) {
+ next.add(displayEntry.id);
+ } else {
+ next.delete(displayEntry.id);
+ }
+ expandedGroups = next;
+ }
+
+ function getGroupedSummaryCount(displayEntry: LogViewerDisplayEntry): number {
+ return Math.max(displayEntry.entries.length - 1, 0);
+ }
</script>
-<div class={cn('log-viewer rounded-t-none rounded-b-xl border bg-black text-white', className)}>
+{#snippet renderLogMessage(entry: LogViewerEntry, contentClass: string)}
+ <div class={contentClass}>
+ {#if entry.isStructured && showParsedJson && isStructuredLogData(entry.parsedJson)}
+ <StructuredLogEntry data={entry.parsedJson} rawJson={entry.message} />
+ {:else}
+ {@html ansiToHtml(entry.message)}
+ {/if}
+ </div>
+{/snippet}
+
+{#snippet renderGroupedSummary(displayEntry: LogViewerDisplayEntry, contentClass: string)}
+ <div class="flex min-w-0 items-start gap-2">
+ <Collapsible.Trigger
+ class="focus-visible:border-ring focus-visible:ring-ring/50 inline-flex shrink-0 items-center gap-1 rounded border border-transparent px-1 py-0.5 text-zinc-500 outline-none hover:bg-white/4 focus-visible:ring-[3px]"
+ >
+ {#if isGroupExpanded(displayEntry)}
+ <ArrowDownIcon class="size-4" />
+ {:else}
+ <ArrowRightIcon class="size-4" />
+ {/if}
+ <span class="text-[11px] font-medium">+{getGroupedSummaryCount(displayEntry)}</span>
+ </Collapsible.Trigger>
+
+ {@render renderLogMessage(displayEntry.entries[0]!, contentClass)}
+ </div>
+{/snippet}
+
+<div
+ class={cn(
+ 'log-viewer rounded-t-none rounded-b-xl border bg-black text-white',
+ fillParent && 'flex h-full min-h-0 flex-col',
+ className
+ )}
+>
{#if error}
<div class="border-b border-red-700 bg-red-900/20 p-3 text-sm text-red-200">
{error}
@@ -420,8 +519,11 @@
<div
bind:this={logContainer}
- class="log-viewer overflow-y-auto rounded-t-none rounded-b-xl border bg-black font-mono text-xs text-white sm:text-sm"
- style="height: {height}; min-height: 300px;"
+ class={cn(
+ 'log-viewer overflow-y-auto rounded-t-none rounded-b-xl border bg-black font-mono text-xs text-white sm:text-sm',
+ fillParent && 'min-h-0 flex-1'
+ )}
+ style={viewportStyle}
role="log"
aria-live={isStreaming ? 'polite' : 'off'}
aria-relevant="additions"
@@ -430,7 +532,7 @@
data-auto-scroll={autoScroll}
data-is-streaming={isStreaming}
>
- {#if logs.length === 0}
+ {#if displayLogs.length === 0}
<div class="p-4 text-center text-gray-500">
{#if !selectedTargetId}
{m.log_viewer_no_selection({ type: humanType })}
@@ -441,52 +543,109 @@
{/if}
</div>
{:else}
- {#each visibleLogs as log (log.id)}
+ {#each displayLogs as displayLog, index (displayLog.key)}
<!-- Mobile view -->
<div
- class="border-l-2 border-transparent px-3 py-2 transition-colors hover:border-blue-500 hover:bg-gray-900/50 sm:hidden"
+ class={cn(
+ 'border-l-2 border-transparent px-3 py-2 transition-colors hover:border-blue-500 hover:bg-gray-900/50 sm:hidden',
+ index % 2 === 1 && 'bg-zinc-900/60'
+ )}
>
- <div class="mb-1 flex items-center gap-2 text-xs">
- {#if type === 'project' && log.service}
- <span class="shrink-0 truncate font-semibold {getServiceColor(log.service)}" title={log.service}>
- {log.service}
+ <div class="mb-1 flex flex-wrap items-center gap-2 text-xs">
+ {#if showTimestamps && getDisplayEntryTimestamp(displayLog)}
+ <span
+ class="inline-flex shrink-0 self-start rounded-md border border-sky-500/15 bg-zinc-900 px-2 py-1 font-semibold text-sky-400 tabular-nums"
+ title={getDisplayEntryTimestamp(displayLog)}
+ >
+ {formatLogTimestamp(getDisplayEntryTimestamp(displayLog))}
</span>
{/if}
- <span class="shrink-0 {getLevelClass(log.level)}">
- {log.level.toUpperCase()}
- </span>
- </div>
- <div class="text-sm break-words whitespace-pre-wrap text-gray-300">
- {#if log.isJson && showParsedJson && typeof log.parsedJson === 'object' && log.parsedJson !== null}
- <StructuredLogEntry data={log.parsedJson} rawJson={log.message} showTimestamp={showTimestamps} />
- {:else}
- {@html ansiToHtml(log.message)}
+ {#if type === 'project' && getDisplayEntryService(displayLog)}
+ <span
+ class="shrink-0 truncate font-semibold {getServiceColor(getDisplayEntryService(displayLog)!)}"
+ title={getDisplayEntryService(displayLog)}
+ >
+ {getDisplayEntryService(displayLog)}
+ </span>
{/if}
+ <span class="shrink-0 {getLevelClass(getDisplayEntryLevel(displayLog))}">
+ {getDisplayEntryLevel(displayLog).toUpperCase()}
+ </span>
</div>
+ {#if displayLog.grouped}
+ <Collapsible.Root
+ open={isGroupExpanded(displayLog)}
+ onOpenChange={(open: boolean) => setGroupExpanded(displayLog, open)}
+ >
+ {@render renderGroupedSummary(displayLog, 'text-sm break-words whitespace-pre-wrap text-gray-300')}
+ <Collapsible.Content>
+ <div class="mt-2 space-y-1.5 border-l border-zinc-800 pl-4">
+ {#each displayLog.entries.slice(1) as entry (entry.id)}
+ {@render renderLogMessage(entry, 'text-sm break-words whitespace-pre-wrap text-gray-300')}
+ {/each}
+ </div>
+ </Collapsible.Content>
+ </Collapsible.Root>
+ {:else}
+ <div class="flex flex-col gap-1.5">
+ {#each displayLog.entries as entry (entry.id)}
+ {@render renderLogMessage(entry, 'text-sm break-words whitespace-pre-wrap text-gray-300')}
+ {/each}
+ </div>
+ {/if}
</div>
<!-- Desktop view -->
<div
- class="hidden border-l-2 border-transparent px-3 py-1 transition-colors hover:border-blue-500 hover:bg-gray-900/50 sm:flex"
+ class={cn(
+ 'hidden items-start border-l-2 border-transparent px-3 py-1.5 transition-colors hover:border-blue-500 hover:bg-gray-900/50 sm:flex',
+ index % 2 === 1 && 'bg-zinc-900/60'
+ )}
>
- {#if type === 'project' && log.service}
+ {#if showTimestamps && getDisplayEntryTimestamp(displayLog)}
<span
- class="mr-3 max-w-[120px] min-w-[120px] shrink-0 truncate text-xs font-semibold {getServiceColor(log.service)}"
- title={log.service}
+ class="mr-3 inline-flex min-w-[178px] shrink-0 self-start rounded-md border border-sky-500/15 bg-zinc-900 px-2.5 py-1 text-[11px] font-semibold text-sky-400 tabular-nums"
+ title={getDisplayEntryTimestamp(displayLog)}
>
- {log.service}
+ {formatLogTimestamp(getDisplayEntryTimestamp(displayLog))}
</span>
{/if}
- <span class="mr-2 shrink-0 text-xs {getLevelClass(log.level)} min-w-fit">
- {log.level.toUpperCase()}
+ {#if type === 'project' && getDisplayEntryService(displayLog)}
+ <span
+ class="mr-3 max-w-[120px] min-w-[120px] shrink-0 truncate text-xs font-semibold {getServiceColor(
+ getDisplayEntryService(displayLog)!
+ )}"
+ title={getDisplayEntryService(displayLog)}
+ >
+ {getDisplayEntryService(displayLog)}
+ </span>
+ {/if}
+ <span class="mr-2 min-w-fit shrink-0 pt-1 text-xs {getLevelClass(getDisplayEntryLevel(displayLog))}">
+ {getDisplayEntryLevel(displayLog).toUpperCase()}
</span>
- <span class="flex-1 break-words whitespace-pre-wrap text-gray-300">
- {#if log.isJson && showParsedJson && typeof log.parsedJson === 'object' && log.parsedJson !== null}
- <StructuredLogEntry data={log.parsedJson} rawJson={log.message} showTimestamp={showTimestamps} />
+ <div class="min-w-0 flex-1">
+ {#if displayLog.grouped}
+ <Collapsible.Root
+ open={isGroupExpanded(displayLog)}
+ onOpenChange={(open: boolean) => setGroupExpanded(displayLog, open)}
+ >
+ {@render renderGroupedSummary(displayLog, 'break-words whitespace-pre-wrap text-gray-300')}
+ <Collapsible.Content>
+ <div class="mt-2 space-y-1 border-l border-zinc-800 pl-4">
+ {#each displayLog.entries.slice(1) as entry (entry.id)}
+ {@render renderLogMessage(entry, 'break-words whitespace-pre-wrap text-gray-300')}
+ {/each}
+ </div>
+ </Collapsible.Content>
+ </Collapsible.Root>
{:else}
- {@html ansiToHtml(log.message)}
+ <div class="flex flex-1 flex-col gap-1">
+ {#each displayLog.entries as entry (entry.id)}
+ {@render renderLogMessage(entry, 'break-words whitespace-pre-wrap text-gray-300')}
+ {/each}
+ </div>
{/if}
- </span>
+ </div>
</div>
{/each}
{/if}
diff --git a/frontend/src/lib/components/logs/log-viewer.utils.ts b/frontend/src/lib/components/logs/log-viewer.utils.ts
new file mode 100644
index 000000000..f1dbd9076
--- /dev/null
+++ b/frontend/src/lib/components/logs/log-viewer.utils.ts
@@ -0,0 +1,293 @@
+import { sanitizeLogText } from '$lib/utils/log-text';
+
+export interface LogViewerEntry {
+ id: number;
+ timestamp: string;
+ level: 'stdout' | 'stderr' | 'info' | 'error';
+ message: string;
+ service?: string;
+ containerId?: string;
+ parsedJson?: unknown;
+ isJson?: boolean;
+ isStructured?: boolean;
+}
+
+export interface LogViewerDisplayEntry {
+ id: number;
+ key: string;
+ grouped: boolean;
+ entries: LogViewerEntry[];
+}
+
+export function buildLogDisplayEntries(
+ logs: LogViewerEntry[],
+ options: {
+ groupAdjacentLines?: boolean;
+ type: 'container' | 'project';
+ }
+): LogViewerDisplayEntry[] {
+ if (!options.groupAdjacentLines || options.type !== 'container') {
+ return logs.map((entry) => ({
+ id: entry.id,
+ key: `single:${entry.id}`,
+ grouped: false,
+ entries: [entry]
+ }));
+ }
+
+ const displayEntries: LogViewerDisplayEntry[] = [];
+
+ for (const entry of logs) {
+ const previous = displayEntries.at(-1);
+ const lastEntry = previous?.entries.at(-1);
+
+ if (previous && lastEntry && canGroupLogEntries(lastEntry, entry)) {
+ previous.entries.push(entry);
+ previous.grouped = true;
+ continue;
+ }
+
+ displayEntries.push({
+ id: entry.id,
+ key: `single:${entry.id}`,
+ grouped: false,
+ entries: [entry]
+ });
+ }
+
+ for (const displayEntry of displayEntries) {
+ if (displayEntry.grouped) {
+ displayEntry.key = `group:${displayEntry.id}`;
+ }
+ }
+
+ return displayEntries;
+}
+
+function canGroupLogEntries(previous: LogViewerEntry, current: LogViewerEntry): boolean {
+ return (
+ !!previous.containerId &&
+ previous.containerId === current.containerId &&
+ previous.level === current.level &&
+ looksLikeMultilineContinuation(previous.message, current.message) &&
+ !previous.isStructured &&
+ !current.isStructured
+ );
+}
+
+function looksLikeMultilineContinuation(previousMessage: string, currentMessage: string): boolean {
+ const previousLine = sanitizeLogText(previousMessage);
+ const currentLine = sanitizeLogText(currentMessage);
+ const currentTrimmed = currentLine.trimStart();
+
+ if (!currentTrimmed) {
+ return true;
+ }
+
+ if (/^\s+/.test(currentLine)) {
+ return true;
+ }
+
+ if (/^[|│]/.test(currentTrimmed)) {
+ return true;
+ }
+
+ if (
+ /^(Traceback\b|File\s+"|Caused by:|During handling of the above exception|The above exception was the direct cause)/.test(
+ currentTrimmed
+ )
+ ) {
+ return true;
+ }
+
+ if (/^(at\s+\S|\.\.\. \d+ more$|[~^]+$)/.test(currentTrimmed)) {
+ return true;
+ }
+
+ if (previousLine.endsWith(':') && /^(Traceback\b|File\s+"|[A-Z][a-zA-Z]+(?:Error|Exception)\b)/.test(currentTrimmed)) {
+ return true;
+ }
+
+ return false;
+}
+
+function unwrapWrappedJson(text: string): string {
+ let candidate = text.trim();
+
+ while (candidate.length >= 2) {
+ const first = candidate[0];
+ const last = candidate.at(-1);
+
+ if (first === '(' && last === ')') {
+ candidate = candidate.slice(1, -1).trim();
+ continue;
+ }
+
+ break;
+ }
+
+ return candidate;
+}
+
+function readQuotedValue(input: string, start: number): { value: string; nextIndex: number } | null {
+ const quote = input[start];
+ if (quote !== '"' && quote !== "'") {
+ return null;
+ }
+
+ let value = '';
+ let index = start + 1;
+ let escaped = false;
+
+ for (; index < input.length; index++) {
+ const char = input[index];
+ if (char === undefined) {
+ break;
+ }
+
+ if (escaped) {
+ value += char;
+ escaped = false;
+ continue;
+ }
+
+ if (char === '\\') {
+ escaped = true;
+ continue;
+ }
+
+ if (char === quote) {
+ return { value, nextIndex: index + 1 };
+ }
+
+ value += char;
+ }
+
+ return null;
+}
+
+function readUnquotedValue(input: string, start: number): { value: string; nextIndex: number } {
+ let index = start;
+
+ for (; index < input.length; index++) {
+ const char = input[index];
+ if (char === undefined || /\s/.test(char)) {
+ break;
+ }
+ }
+
+ return {
+ value: input.slice(start, index),
+ nextIndex: index
+ };
+}
+
+function coerceStructuredValue(value: string): unknown {
+ const trimmed = value.trim();
+ if (!trimmed) return '';
+ if (trimmed === 'true') return true;
+ if (trimmed === 'false') return false;
+ if (trimmed === 'null') return null;
+ if (/^-?\d+(?:\.\d+)?$/.test(trimmed)) {
+ const numeric = Number(trimmed);
+ if (!Number.isNaN(numeric)) {
+ return numeric;
+ }
+ }
+
+ return trimmed;
+}
+
+function tryParseLogfmt(message: string): Record<string, unknown> | null {
+ const trimmed = message.trim();
+ if (!trimmed || !trimmed.includes('=')) {
+ return null;
+ }
+
+ const parsed: Record<string, unknown> = {};
+ let index = 0;
+
+ while (index < trimmed.length) {
+ while (index < trimmed.length && /\s/.test(trimmed[index]!)) {
+ index++;
+ }
+
+ if (index >= trimmed.length) {
+ break;
+ }
+
+ const keyStart = index;
+ while (index < trimmed.length) {
+ const char = trimmed[index];
+ if (char === undefined || char === '=' || /\s/.test(char)) {
+ break;
+ }
+ index++;
+ }
+
+ const key = trimmed.slice(keyStart, index);
+ if (!key) {
+ return null;
+ }
+
+ if (trimmed[index] !== '=') {
+ return null;
+ }
+
+ index++;
+ if (index >= trimmed.length) {
+ parsed[key] = '';
+ break;
+ }
+
+ const next = trimmed[index];
+ const valueResult = next === '"' || next === "'" ? readQuotedValue(trimmed, index) : readUnquotedValue(trimmed, index);
+
+ if (!valueResult) {
+ return null;
+ }
+
+ parsed[key] = coerceStructuredValue(valueResult.value);
+ index = valueResult.nextIndex;
+ }
+
+ return Object.keys(parsed).length > 0 ? parsed : null;
+}
+
+export function tryParseStructuredLog(message: string): {
+ isJson: boolean;
+ isStructured: boolean;
+ parsed?: Record<string, unknown> | unknown[];
+} {
+ const trimmed = sanitizeLogText(message).trim();
+ if (!trimmed) {
+ return { isJson: false, isStructured: false };
+ }
+
+ const jsonCandidate = unwrapWrappedJson(trimmed);
+ if (jsonCandidate.startsWith('{') || jsonCandidate.startsWith('[')) {
+ try {
+ const parsed = JSON.parse(jsonCandidate);
+ if (parsed && typeof parsed === 'object') {
+ return {
+ isJson: true,
+ isStructured: true,
+ parsed
+ };
+ }
+ } catch {
+ // Fall through to logfmt parsing.
+ }
+ }
+
+ const logfmtParsed = tryParseLogfmt(trimmed);
+ if (logfmtParsed) {
+ return {
+ isJson: false,
+ isStructured: true,
+ parsed: logfmtParsed
+ };
+ }
+
+ return { isJson: false, isStructured: false };
+}
diff --git a/frontend/src/lib/components/logs/structured-log-entry.svelte b/frontend/src/lib/components/logs/structured-log-entry.svelte
index 843eacfe7..9d40b50c4 100644
--- a/frontend/src/lib/components/logs/structured-log-entry.svelte
+++ b/frontend/src/lib/components/logs/structured-log-entry.svelte
@@ -1,38 +1,44 @@
<script lang="ts">
- import { CopyIcon, CheckIcon } from '$lib/icons';
+ // Dozzle reference: the compact structured-log summary and expandable details pattern
+ // here were informed by amir20/dozzle's ComplexLogItem.vue and LogDetails.vue.
+ import * as Collapsible from '$lib/components/ui/collapsible';
+ import { ArrowDownIcon, ArrowRightIcon, CheckIcon, CopyIcon } from '$lib/icons';
interface Props {
data: Record<string, unknown>;
rawJson?: string;
- showTimestamp?: boolean;
}
- let { data, rawJson, showTimestamp = false }: Props = $props();
+ type SummaryField = {
+ path: string;
+ label: string;
+ value: unknown;
+ };
+
+ let { data, rawJson }: Props = $props();
let showDetails = $state(false);
let copied = $state(false);
+ const SUMMARY_LIMIT = 6;
+
// Common field names used by various structured logging frameworks
- // Supports: Rust (tracing, slog), Go (zap, zerolog, logrus), Node (pino, winston, bunyan),
- // Python (structlog), Java (Log4j2), .NET (Serilog), and more
const LEVEL_KEYS = ['level', 'severity', 'log.level', 'loglevel', 'lvl', 'levelname', 'priority'];
const MESSAGE_KEYS = ['message', 'msg', 'text', 'body', 'event', 'log', 'content'];
const TIMESTAMP_KEYS = ['timestamp', 'time', 'ts', '@timestamp', 'datetime', 'date', 'created', 'time_local'];
const TARGET_KEYS = ['target', 'logger', 'name', 'source', 'component', 'module', 'log.logger', 'logger_name', 'category'];
const ERROR_KEYS = ['error', 'err', 'exception', 'stack', 'stacktrace', 'error.message'];
const TRACE_KEYS = ['trace_id', 'traceId', 'correlation_id', 'correlationId', 'request_id', 'requestId', 'spanId', 'span_id'];
-
- // Nested message location (e.g., tracing-subscriber in Rust uses fields.message)
const NESTED_MESSAGE_PATHS = [
['fields', 'message'],
['fields', 'msg'],
['data', 'message']
];
+ const HIDDEN_SUMMARY_KEYS = new Set([...LEVEL_KEYS, ...MESSAGE_KEYS, ...TIMESTAMP_KEYS]);
function findValue(obj: Record<string, unknown>, keys: string[]): unknown {
for (const key of keys) {
if (key in obj) return obj[key];
- // Handle dot notation keys like 'log.level'
if (key.includes('.')) {
const parts = key.split('.');
let current: unknown = obj;
@@ -69,7 +75,6 @@
function normalizeLevelValue(level: unknown): string | undefined {
if (typeof level === 'string') return level;
if (typeof level === 'number') {
- // Syslog levels: 0=emerg, 1=alert, 2=crit, 3=error, 4=warn, 5=notice, 6=info, 7=debug
const syslogMap: Record<number, string> = {
0: 'fatal',
1: 'fatal',
@@ -85,31 +90,23 @@
return undefined;
}
- function normalizeTimestamp(ts: unknown): string | undefined {
- if (typeof ts === 'string') return ts;
- if (typeof ts === 'number') {
- // Handle Unix timestamps (seconds or milliseconds)
- const timestamp = ts > 1e12 ? ts : ts * 1000; // Convert to ms if in seconds
- return new Date(timestamp).toISOString();
- }
- return undefined;
- }
-
- function extractFields(obj: Record<string, unknown>) {
+ function extractFields(obj: Record<string, unknown>): {
+ level: string | undefined;
+ message: string | undefined;
+ target: string | undefined;
+ error: unknown;
+ traceId: string | undefined;
+ hasStructure: boolean;
+ } {
const rawLevel = findValue(obj, LEVEL_KEYS);
let message = findValue(obj, MESSAGE_KEYS);
-
- // Try nested paths if no top-level message found
if (!message) {
message = findNestedMessage(obj);
}
-
- // Fallback: use 'event' field if no message found
if (!message && obj['event']) {
message = String(obj['event']);
}
- const rawTimestamp = findValue(obj, TIMESTAMP_KEYS);
const target = findValue(obj, TARGET_KEYS);
const error = findValue(obj, ERROR_KEYS);
const traceId = findValue(obj, TRACE_KEYS);
@@ -117,62 +114,116 @@
return {
level: normalizeLevelValue(rawLevel),
message: typeof message === 'string' ? message : undefined,
- timestamp: normalizeTimestamp(rawTimestamp),
target: typeof target === 'string' ? target : undefined,
- error: error !== undefined ? error : undefined,
+ error,
traceId: typeof traceId === 'string' ? traceId : undefined,
- hasStructure: !!(rawLevel || message || rawTimestamp || target)
+ hasStructure: !!(rawLevel || message || target)
};
}
- function getLevelColor(level: string | undefined): string {
- if (!level) return 'text-gray-400';
- const l = level.toLowerCase();
- if (l === 'error' || l === 'err' || l === 'fatal' || l === 'critical' || l === 'panic' || l === 'emergency')
- return 'text-red-400';
- if (l === 'warn' || l === 'warning' || l === 'alert') return 'text-yellow-400';
- if (l === 'info' || l === 'information' || l === 'notice') return 'text-green-400';
- if (l === 'debug' || l === 'dbg') return 'text-blue-400';
- if (l === 'trace' || l === 'verbose' || l === 'finest') return 'text-purple-400';
- return 'text-gray-400';
+ function getLevelDotClass(level: string | undefined): string {
+ if (!level) return 'bg-zinc-500';
+ const normalizedLevel = level.toLowerCase();
+ if (
+ normalizedLevel === 'error' ||
+ normalizedLevel === 'err' ||
+ normalizedLevel === 'fatal' ||
+ normalizedLevel === 'critical' ||
+ normalizedLevel === 'panic' ||
+ normalizedLevel === 'emergency'
+ ) {
+ return 'bg-red-400';
+ }
+ if (normalizedLevel === 'warn' || normalizedLevel === 'warning' || normalizedLevel === 'alert') {
+ return 'bg-orange-400';
+ }
+ if (normalizedLevel === 'info' || normalizedLevel === 'information' || normalizedLevel === 'notice') {
+ return 'bg-emerald-400';
+ }
+ if (normalizedLevel === 'debug' || normalizedLevel === 'dbg') {
+ return 'bg-sky-400';
+ }
+ if (normalizedLevel === 'trace' || normalizedLevel === 'verbose' || normalizedLevel === 'finest') {
+ return 'bg-violet-400';
+ }
+ return 'bg-zinc-500';
}
- function getLevelBgColor(level: string | undefined): string {
- if (!level) return 'bg-gray-800';
- const l = level.toLowerCase();
- if (l === 'error' || l === 'err' || l === 'fatal' || l === 'critical' || l === 'panic' || l === 'emergency')
- return 'bg-red-900/30';
- if (l === 'warn' || l === 'warning' || l === 'alert') return 'bg-yellow-900/30';
- if (l === 'info' || l === 'information' || l === 'notice') return 'bg-green-900/30';
- if (l === 'debug' || l === 'dbg') return 'bg-blue-900/30';
- if (l === 'trace' || l === 'verbose' || l === 'finest') return 'bg-purple-900/30';
- return 'bg-gray-800';
+ function safeStringify(value: unknown, indent = 0): string {
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (value === null) {
+ return 'null';
+ }
+ if (value === undefined) {
+ return '';
+ }
+ try {
+ return JSON.stringify(value, null, indent);
+ } catch {
+ return String(value);
+ }
}
- function formatTimestamp(ts: string | undefined): string {
- if (!ts) return '';
- try {
- const date = new Date(ts);
- if (isNaN(date.getTime())) return ts;
- return date.toLocaleTimeString('en-US', {
- hour12: false,
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- fractionalSecondDigits: 3
+ function formatInlineValue(value: unknown): string {
+ if (value === null) {
+ return '<null>';
+ }
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ return String(value);
+ }
+
+ const compact = safeStringify(value);
+ if (compact.length <= 72) {
+ return compact;
+ }
+
+ return `${compact.slice(0, 69)}...`;
+ }
+
+ function buildSummaryFields(obj: Record<string, unknown>): SummaryField[] {
+ const fields: SummaryField[] = [];
+
+ for (const [key, value] of Object.entries(obj)) {
+ if (value === undefined || HIDDEN_SUMMARY_KEYS.has(key)) {
+ continue;
+ }
+
+ if ((key === 'fields' || key === 'data') && value && typeof value === 'object' && !Array.isArray(value)) {
+ for (const [nestedKey, nestedValue] of Object.entries(value as Record<string, unknown>)) {
+ if (nestedValue === undefined || MESSAGE_KEYS.includes(nestedKey)) {
+ continue;
+ }
+
+ fields.push({
+ path: `${key}.${nestedKey}`,
+ label: nestedKey,
+ value: nestedValue
+ });
+ }
+ continue;
+ }
+
+ fields.push({
+ path: key,
+ label: key,
+ value
});
- } catch {
- return ts;
}
+
+ return fields;
}
const extracted = $derived(extractFields(data));
- const formattedTime = $derived(formatTimestamp(extracted.timestamp));
- const levelDisplay = $derived(extracted.level?.toUpperCase() ?? 'LOG');
+ const summaryFields = $derived(buildSummaryFields(data));
+ const visibleSummaryFields = $derived(summaryFields.slice(0, SUMMARY_LIMIT));
+ const hiddenSummaryCount = $derived(Math.max(summaryFields.length - visibleSummaryFields.length, 0));
const jsonString = $derived(rawJson ?? JSON.stringify(data, null, 2));
-
- // For unstructured JSON, create a compact string representation
- const compactJson = $derived(JSON.stringify(data));
+ const hasDetails = $derived(summaryFields.length > SUMMARY_LIMIT || summaryFields.length > 0 || !!rawJson);
async function copyToClipboard() {
try {
@@ -187,50 +238,89 @@
}
</script>
-<div class="structured-log-entry">
- <!-- Main log line with extracted fields -->
- <div class="flex items-start gap-2">
- <!-- Level badge -->
- <span
- class="shrink-0 rounded px-1.5 py-0.5 text-xs font-semibold {getLevelColor(extracted.level)} {getLevelBgColor(
- extracted.level
- )}"
- >
- {levelDisplay}
- </span>
-
- <!-- Timestamp (if available and enabled) -->
- {#if showTimestamp && formattedTime}
- <span class="shrink-0 text-xs text-gray-500" title={extracted.timestamp}>
- {formattedTime}
- </span>
- {/if}
+<Collapsible.Root bind:open={showDetails}>
+ <div class="flex min-w-0 items-start gap-2">
+ {#if hasDetails}
+ <Collapsible.Trigger
+ class="focus-visible:border-ring focus-visible:ring-ring/50 flex min-w-0 flex-1 items-start gap-3 rounded-md border border-transparent px-1 py-0.5 text-left outline-none hover:bg-white/3 focus-visible:ring-[3px]"
+ >
+ {#if extracted.level}
+ <span class="mt-1.5 size-2.5 shrink-0 rounded-full {getLevelDotClass(extracted.level)}"></span>
+ {/if}
- <!-- Target/Logger name -->
- {#if extracted.target}
- <span class="shrink-0 text-xs font-medium text-cyan-400" title={extracted.target}>
- [{extracted.target}]
- </span>
- {/if}
+ <div class="min-w-0 flex-1">
+ <div class="flex flex-wrap items-center gap-x-4 gap-y-1">
+ {#if extracted.target}
+ <span class="truncate text-[11px] font-medium text-cyan-400" title={extracted.target}>
+ {extracted.target}
+ </span>
+ {/if}
- <!-- Message -->
- <span class="flex-1 text-gray-200">
- {#if extracted.message}
- {extracted.message}
- {:else if !extracted.hasStructure}
- <!-- For unstructured JSON, display as compact string -->
- <span class="text-gray-300">{compactJson}</span>
- {:else}
- <span class="text-gray-500 italic">No message field</span>
- {/if}
- </span>
+ {#if extracted.message}
+ <span class="min-w-0 text-gray-100">{extracted.message}</span>
+ {:else if !extracted.hasStructure}
+ <span class="min-w-0 text-gray-300">{safeStringify(data)}</span>
+ {/if}
+
+ {#each visibleSummaryFields as field (field.path)}
+ <span class="inline-flex max-w-full min-w-0 items-baseline gap-0.5 text-gray-300">
+ <span class="shrink-0 text-zinc-500">{field.label}=</span>
+ <span class="truncate font-semibold text-zinc-100" title={safeStringify(field.value)}>
+ {formatInlineValue(field.value)}
+ </span>
+ </span>
+ {/each}
+
+ {#if hiddenSummaryCount > 0}
+ <span class="text-[11px] font-medium text-zinc-500">+{hiddenSummaryCount}</span>
+ {/if}
+ </div>
+ </div>
+
+ {#if showDetails}
+ <ArrowDownIcon class="mt-0.5 size-4 shrink-0 text-zinc-500" />
+ {:else}
+ <ArrowRightIcon class="mt-0.5 size-4 shrink-0 text-zinc-500" />
+ {/if}
+ </Collapsible.Trigger>
+ {:else}
+ <div class="flex min-w-0 flex-1 items-start gap-3 px-1 py-0.5">
+ {#if extracted.level}
+ <span class="mt-1.5 size-2.5 shrink-0 rounded-full {getLevelDotClass(extracted.level)}"></span>
+ {/if}
+
+ <div class="min-w-0 flex-1">
+ <div class="flex flex-wrap items-center gap-x-4 gap-y-1">
+ {#if extracted.target}
+ <span class="truncate text-[11px] font-medium text-cyan-400" title={extracted.target}>
+ {extracted.target}
+ </span>
+ {/if}
+
+ {#if extracted.message}
+ <span class="min-w-0 text-gray-100">{extracted.message}</span>
+ {:else if !extracted.hasStructure}
+ <span class="min-w-0 text-gray-300">{safeStringify(data)}</span>
+ {/if}
+
+ {#each visibleSummaryFields as field (field.path)}
+ <span class="inline-flex max-w-full min-w-0 items-baseline gap-0.5 text-gray-300">
+ <span class="shrink-0 text-zinc-500">{field.label}=</span>
+ <span class="truncate font-semibold text-zinc-100" title={safeStringify(field.value)}>
+ {formatInlineValue(field.value)}
+ </span>
+ </span>
+ {/each}
+ </div>
+ </div>
+ </div>
+ {/if}
- <!-- Copy to clipboard button -->
<button
type="button"
onclick={copyToClipboard}
- class="shrink-0 rounded p-1 text-gray-500 transition-colors hover:bg-gray-700 hover:text-gray-200"
- title={copied ? 'Copied!' : 'Copy JSON'}
+ class="shrink-0 rounded p-1 text-zinc-500 transition-colors hover:bg-white/5 hover:text-zinc-100"
+ title={copied ? 'Copied' : 'Copy JSON'}
>
{#if copied}
<CheckIcon class="size-3.5 text-green-400" />
@@ -238,22 +328,27 @@
<CopyIcon class="size-3.5" />
{/if}
</button>
-
- <!-- Details toggle button - always show to expand full JSON -->
- <button
- type="button"
- onclick={() => (showDetails = !showDetails)}
- class="shrink-0 rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-gray-700 hover:text-gray-200"
- title={showDetails ? 'Hide JSON' : 'Show full JSON'}
- >
- {showDetails ? '▼' : '▶'}
- </button>
</div>
- <!-- Collapsible full JSON section -->
- {#if showDetails}
- <div class="mt-1 ml-4 border-l border-gray-700 pl-2">
- <pre class="text-xs break-all whitespace-pre-wrap text-gray-300">{JSON.stringify(data, null, 2)}</pre>
- </div>
+ {#if hasDetails}
+ <Collapsible.Content>
+ <div class="mt-2 rounded-md border border-zinc-800 bg-zinc-950/75 p-3">
+ {#if summaryFields.length > 0}
+ <div class="grid gap-x-4 gap-y-2 md:grid-cols-[minmax(140px,180px)_1fr]">
+ {#each summaryFields as field (field.path)}
+ <div class="font-mono text-[11px] text-zinc-500">{field.path}</div>
+ <pre class="overflow-x-auto text-xs break-all whitespace-pre-wrap text-zinc-100">{safeStringify(
+ field.value,
+ 2
+ )}</pre>
+ {/each}
+ </div>
+ {/if}
+
+ <div class="mt-3 border-t border-zinc-800 pt-3">
+ <pre class="overflow-x-auto text-xs break-all whitespace-pre-wrap text-zinc-300">{jsonString}</pre>
+ </div>
+ </div>
+ </Collapsible.Content>
{/if}
-</div>
+</Collapsible.Root>
diff --git a/frontend/src/lib/types/container.type.ts b/frontend/src/lib/types/container.type.ts
index 2cef85877..d0555f50c 100644
--- a/frontend/src/lib/types/container.type.ts
+++ b/frontend/src/lib/types/container.type.ts
@@ -292,6 +292,12 @@ export interface StorageStats {
write_size_bytes?: number;
}
+export interface ContainerStatsHistorySample {
+ cpuTenths: number;
+ memoryTenths: number;
+ memoryUsageBytes: number;
+}
+
export interface ContainerStats {
id: string;
name: string;
@@ -305,4 +311,6 @@ export interface ContainerStats {
memory_stats: MemoryStats;
networks: Record<string, NetworkStats>;
storage_stats: StorageStats;
+ statsHistory?: ContainerStatsHistorySample[];
+ currentHistorySample?: ContainerStatsHistorySample;
}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index b1b74c40c..49febb459 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -102,10 +102,6 @@
await invalidateAll();
}
- function handleLogClear() {
- void invalidateAll();
- }
-
const hasEnvVars = $derived(!!(container?.config?.env && container.config.env.length > 0));
const hasPorts = $derived(!!(container?.ports && container.ports.length > 0));
const hasLabels = $derived(!!(container?.labels && Object.keys(container.labels).length > 0));
@@ -210,7 +206,7 @@
{#if container}
<ContainerDetailStatsSync
containerId={container.id}
- enabled={activeTab === 'stats' && !!container.state?.running}
+ enabled={(activeTab === 'stats' || activeTab === 'logs') && !!container.state?.running}
bind:stats
bind:hasInitialStatsLoaded
/>
@@ -275,7 +271,14 @@
<Tabs.Content value="logs" class="h-full">
{#if activeTab === 'logs'}
- <ContainerLogsPanel containerId={container?.id} bind:autoScroll={autoScrollLogs} onClear={handleLogClear} />
+ <ContainerLogsPanel
+ containerId={container?.id}
+ {stats}
+ {hasInitialStatsLoaded}
+ isRunning={!!container.state?.running}
+ {cpuLimit}
+ bind:autoScroll={autoScrollLogs}
+ />
{/if}
</Tabs.Content>
diff --git a/frontend/src/routes/(app)/containers/components/ContainerLogStatMonitor.svelte b/frontend/src/routes/(app)/containers/components/ContainerLogStatMonitor.svelte
new file mode 100644
index 000000000..7c7e9c1bf
--- /dev/null
+++ b/frontend/src/routes/(app)/containers/components/ContainerLogStatMonitor.svelte
@@ -0,0 +1,79 @@
+<script lang="ts">
+ import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
+ import type { IconType } from '$lib/icons';
+ import { Skeleton } from '$lib/components/ui/skeleton';
+ import { cn } from '$lib/utils';
+
+ interface Props {
+ icon: IconType;
+ label: string;
+ value: string;
+ detail: string;
+ history: Array<{ percent: number; tooltip: string }>;
+ tone?: 'cpu' | 'memory';
+ loading?: boolean;
+ disabled?: boolean;
+ testId?: string;
+ }
+
+ let { icon, label, value, detail, history, tone = 'cpu', loading = false, disabled = false, testId }: Props = $props();
+
+ const barColorClass = $derived(tone === 'cpu' ? 'bg-sky-400/75' : 'bg-emerald-400/75');
+ const iconColorClass = $derived(tone === 'cpu' ? 'text-sky-300' : 'text-emerald-300');
+ const Icon = $derived(icon);
+</script>
+
+<section
+ class={cn(
+ 'bg-card/35 border-border/70 grid min-w-0 gap-2 rounded-lg border px-3 py-2.5',
+ disabled && 'bg-muted/25 text-muted-foreground'
+ )}
+ data-testid={testId}
+>
+ <div class="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3">
+ <div class="flex min-w-0 items-center gap-2">
+ <div class="bg-background/70 flex size-7 shrink-0 items-center justify-center rounded-md border border-white/8">
+ <Icon class={cn('size-4', disabled ? 'text-muted-foreground' : iconColorClass)} />
+ </div>
+ <div class="min-w-0">
+ <div class="text-[11px] font-medium tracking-normal text-white/70">{label}</div>
+ {#if loading}
+ <Skeleton class="mt-1 h-5 w-20" />
+ {:else}
+ <div class={cn('truncate text-sm font-semibold tabular-nums', disabled ? 'text-muted-foreground' : 'text-white')}>
+ {value}
+ </div>
+ {/if}
+ </div>
+ </div>
+
+ {#if loading}
+ <Skeleton class="mt-0.5 h-4 w-16 justify-self-end" />
+ {:else}
+ <div class="shrink-0 justify-self-end pl-2 text-right text-[11px] text-white/55 tabular-nums">{detail}</div>
+ {/if}
+ </div>
+
+ {#if loading}
+ <Skeleton class="h-8 w-full" />
+ {:else}
+ <div class="bg-background/60 flex h-8 items-end gap-[3px] overflow-hidden rounded-md border border-white/8 px-1.5 py-1">
+ {#each history as sample, index (`${tone}-${index}`)}
+ <ArcaneTooltip.Root>
+ <ArcaneTooltip.Trigger class="flex h-full min-w-0 flex-1 items-end self-stretch">
+ <div
+ class={cn('min-w-0 flex-1 rounded-[2px] transition-opacity', disabled ? 'bg-white/8' : barColorClass)}
+ style={`height: ${Math.max(disabled ? 12 : Math.min(Math.max(sample.percent, 6), 100), 6)}%; opacity: ${disabled ? 0.35 : 0.45 + Math.min(sample.percent, 100) / 180};`}
+ ></div>
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content side="top">
+ <div class="space-y-1">
+ <div class="text-xs font-medium">{label}</div>
+ <div class="text-muted-foreground text-xs tabular-nums">{sample.tooltip}</div>
+ </div>
+ </ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
+ {/each}
+ </div>
+ {/if}
+</section>
diff --git a/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte b/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
index 5a85d0cfa..199ed353e 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
@@ -1,22 +1,37 @@
<script lang="ts">
+ // Dozzle reference: the compact CPU/memory monitors in the logs header were informed
+ // by amir20/dozzle's ContainerLog.vue and MultiContainerStat.vue.
import * as Card from '$lib/components/ui/card';
import LogViewer from '$lib/components/logs/log-viewer.svelte';
import LogControls from '$lib/components/logs/log-controls.svelte';
+ import type { ContainerStats, ContainerStatsHistorySample } from '$lib/types/container.type';
import { m } from '$lib/paraglide/messages';
- import { FileTextIcon } from '$lib/icons';
+ import bytes from '$lib/utils/bytes';
+ import { calculateCPUPercent, calculateMemoryUsage } from '$lib/utils/container-stats.utils';
+ import { CpuIcon, FileTextIcon, MemoryStickIcon } from '$lib/icons';
+ import ContainerLogStatMonitor from './ContainerLogStatMonitor.svelte';
+
+ const HISTORY_LIMIT = 30;
+ type StatHistoryPoint = { percent: number; tooltip: string };
let {
containerId,
+ stats = null,
+ hasInitialStatsLoaded = false,
+ isRunning = false,
+ cpuLimit = 0,
autoScroll = $bindable(),
onStart,
- onStop,
- onClear
+ onStop
}: {
containerId: string | undefined;
+ stats?: ContainerStats | null;
+ hasInitialStatsLoaded?: boolean;
+ isRunning?: boolean;
+ cpuLimit?: number;
autoScroll: boolean;
onStart?: () => void;
onStop?: () => void;
- onClear: () => void;
} = $props();
let isStreaming = $state(false);
@@ -24,6 +39,96 @@
let autoStartLogs = $state(false);
let hasAutoStarted = $state(false);
let showParsedJson = $state(false);
+ let cpuHistory = $state<StatHistoryPoint[]>([]);
+ let memoryHistory = $state<StatHistoryPoint[]>([]);
+ let cpuHistoryAccumulator: StatHistoryPoint[] = [];
+ let memoryHistoryAccumulator: StatHistoryPoint[] = [];
+ let lastStatsRead: string | null = null;
+
+ const cpuUsagePercent = $derived(calculateCPUPercent(stats));
+ const memoryUsageBytes = $derived(calculateMemoryUsage(stats));
+ const memoryLimitBytes = $derived(stats?.memory_stats?.limit || 0);
+ const memoryUsagePercent = $derived.by(() => {
+ if (!memoryLimitBytes) return 0;
+ return Math.min(Math.max((memoryUsageBytes / memoryLimitBytes) * 100, 0), 100);
+ });
+ const cpuValue = $derived(isRunning ? `${cpuUsagePercent.toFixed(1)}%` : m.common_na());
+ const cpuDetail = $derived.by(() => {
+ if (!isRunning) return m.common_na();
+ if (cpuLimit > 0) {
+ const rounded = Number.isInteger(cpuLimit) ? cpuLimit.toFixed(0) : cpuLimit.toFixed(1);
+ return `${rounded} ${cpuLimit === 1 ? m.containers_stats_cpu_unit_singular() : m.common_cpus()}`;
+ }
+ const onlineCpus = stats?.cpu_stats?.online_cpus ?? 0;
+ return onlineCpus > 0
+ ? `${onlineCpus} ${onlineCpus === 1 ? m.containers_stats_cpu_unit_singular() : m.common_cpus()}`
+ : m.common_na();
+ });
+ const memoryValue = $derived(isRunning ? bytes.format(memoryUsageBytes, { unitSeparator: ' ' }) : m.common_na());
+ const memoryDetail = $derived.by(() => {
+ if (!isRunning) return m.common_na();
+ if (!memoryLimitBytes) return m.common_na();
+ return bytes.format(memoryLimitBytes, { unitSeparator: ' ' });
+ });
+
+ function resetHistory() {
+ cpuHistoryAccumulator = [];
+ memoryHistoryAccumulator = [];
+ cpuHistory = [];
+ memoryHistory = [];
+ lastStatsRead = null;
+ }
+
+ function appendHistorySample(history: StatHistoryPoint[], value: StatHistoryPoint): StatHistoryPoint[] {
+ const next = [...history, value];
+ if (next.length > HISTORY_LIMIT) {
+ next.shift();
+ }
+ return next;
+ }
+
+ function percentFromTenths(tenths: number | undefined): number {
+ if (typeof tenths !== 'number' || Number.isNaN(tenths)) {
+ return 0;
+ }
+
+ return Math.min(Math.max(tenths / 10, 0), 100);
+ }
+
+ function formatPercent(value: number, digits = 2): string {
+ if (value > 0 && value < 0.01) {
+ return '<0.01%';
+ }
+
+ return `${value.toFixed(digits)}%`;
+ }
+
+ function toCPUHistoryPoint(sample: ContainerStatsHistorySample): StatHistoryPoint {
+ const percent = percentFromTenths(sample.cpuTenths);
+ return {
+ percent,
+ tooltip: formatPercent(percent, 1)
+ };
+ }
+
+ function toMemoryHistoryPoint(sample: ContainerStatsHistorySample): StatHistoryPoint {
+ const percent = percentFromTenths(sample.memoryTenths);
+ const usage = bytes.format(sample.memoryUsageBytes || 0, { unitSeparator: ' ' });
+ const limit = memoryLimitBytes ? bytes.format(memoryLimitBytes, { unitSeparator: ' ' }) : '';
+
+ return {
+ percent,
+ tooltip: limit ? `${usage} / ${limit} (${formatPercent(percent, 2)})` : `${usage} (${formatPercent(percent, 2)})`
+ };
+ }
+
+ function applyBackendHistory(samples: ContainerStatsHistorySample[] | undefined) {
+ const history = samples ?? [];
+ cpuHistoryAccumulator = history.map(toCPUHistoryPoint);
+ memoryHistoryAccumulator = history.map(toMemoryHistoryPoint);
+ cpuHistory = cpuHistoryAccumulator;
+ memoryHistory = memoryHistoryAccumulator;
+ }
function handleStart() {
viewer?.startLogStream();
@@ -33,11 +138,6 @@
viewer?.stopLogStream();
}
- function handleClear() {
- viewer?.clearLogs();
- onClear();
- }
-
async function handleRefresh() {
await viewer?.clearLogs({ hard: true, restart: true });
}
@@ -56,6 +156,7 @@
$effect(() => {
if (containerId) {
hasAutoStarted = false;
+ resetHistory();
}
});
@@ -65,11 +166,35 @@
handleStart();
}
});
+
+ $effect(() => {
+ if (!isRunning) {
+ return;
+ }
+
+ if (stats?.statsHistory?.length) {
+ applyBackendHistory(stats.statsHistory);
+ lastStatsRead = stats.read;
+ return;
+ }
+
+ if (!stats?.read || stats.read === lastStatsRead) {
+ return;
+ }
+
+ lastStatsRead = stats.read;
+ if (stats.currentHistorySample) {
+ cpuHistoryAccumulator = appendHistorySample(cpuHistoryAccumulator, toCPUHistoryPoint(stats.currentHistorySample));
+ memoryHistoryAccumulator = appendHistorySample(memoryHistoryAccumulator, toMemoryHistoryPoint(stats.currentHistorySample));
+ cpuHistory = cpuHistoryAccumulator;
+ memoryHistory = memoryHistoryAccumulator;
+ }
+ });
</script>
-<Card.Root>
+<Card.Root class="flex h-full min-h-0 flex-col">
<Card.Header icon={FileTextIcon}>
- <div class="flex flex-1 flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
+ <div class="flex flex-1 flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div class="flex flex-col gap-1.5">
<div class="flex items-center gap-2">
<Card.Title>
@@ -94,13 +219,38 @@
disabled={!containerId}
onStart={handleStart}
onStop={handleStop}
- onClear={handleClear}
onRefresh={handleRefresh}
/>
</div>
</Card.Header>
- <Card.Content class="p-0">
- <div class="bg-card/90 rounded-lg border p-0 backdrop-blur-sm">
+ <Card.Content class="flex min-h-0 flex-1 flex-col p-0">
+ <div class="shrink-0 border-b px-4 pb-4" data-testid="container-log-stats">
+ <div class="grid gap-3 md:grid-cols-2">
+ <ContainerLogStatMonitor
+ icon={CpuIcon}
+ label={m.dashboard_meter_cpu()}
+ value={cpuValue}
+ detail={cpuDetail}
+ history={cpuHistory}
+ tone="cpu"
+ loading={isRunning && !hasInitialStatsLoaded}
+ disabled={!isRunning}
+ testId="container-log-cpu-monitor"
+ />
+ <ContainerLogStatMonitor
+ icon={MemoryStickIcon}
+ label={m.dashboard_meter_memory()}
+ value={memoryValue}
+ detail={memoryDetail}
+ history={memoryHistory}
+ tone="memory"
+ loading={isRunning && !hasInitialStatsLoaded}
+ disabled={!isRunning}
+ testId="container-log-memory-monitor"
+ />
+ </div>
+ </div>
+ <div class="bg-card/90 min-h-0 flex-1 overflow-hidden rounded-lg border p-0 backdrop-blur-sm">
<LogViewer
bind:this={viewer}
bind:autoScroll
@@ -109,10 +259,10 @@
{showParsedJson}
maxLines={500}
showTimestamps={true}
- height="calc(100vh - 320px)"
+ groupAdjacentLines={true}
+ height="100%"
onStart={handleStreamStart}
onStop={handleStreamStop}
- {onClear}
/>
</div>
</Card.Content>
diff --git a/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte b/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte
index 015eb9b09..93646ecf6 100644
--- a/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte
+++ b/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte
@@ -30,10 +30,6 @@
viewer?.stopLogStream();
}
- function handleClear() {
- viewer?.clearLogs();
- }
-
async function handleRefresh() {
await viewer?.clearLogs({ hard: true, restart: true });
}
@@ -78,7 +74,6 @@
disabled={!projectId}
onStart={handleStart}
onStop={handleStop}
- onClear={handleClear}
onRefresh={handleRefresh}
/>
</div>
diff --git a/tests/spec/containers.spec.ts b/tests/spec/containers.spec.ts
index fb9a464ed..62981049c 100644
--- a/tests/spec/containers.spec.ts
+++ b/tests/spec/containers.spec.ts
@@ -59,6 +59,44 @@ test.describe('Containers Page', () => {
).toBeVisible();
});
+ test('should show live CPU and memory monitors on the logs tab for running containers', async ({
+ page
+ }) => {
+ const running = containersData.data.find((c) => c.state === 'running');
+ test.skip(!running, 'No running container available');
+
+ await page.goto(`/containers/${running!.id}`);
+ await page.waitForLoadState('networkidle');
+
+ await page.getByRole('tab', { name: 'Logs' }).click();
+
+ await expect(page.locator('[data-testid="container-log-cpu-monitor"]')).toBeVisible();
+ await expect(page.locator('[data-testid="container-log-memory-monitor"]')).toBeVisible();
+ await expect(page.locator('[data-testid="container-log-cpu-monitor"]')).not.toContainText(
+ 'N/A'
+ );
+ await expect(page.locator('[data-testid="container-log-memory-monitor"]')).not.toContainText(
+ 'N/A'
+ );
+ });
+
+ test('should show non-live fallback monitors on the logs tab for stopped containers', async ({
+ page
+ }) => {
+ const stopped = containersData.data.find((c) => c.state !== 'running');
+ test.skip(!stopped, 'No stopped container available');
+
+ await page.goto(`/containers/${stopped!.id}`);
+ await page.waitForLoadState('networkidle');
+
+ await page.getByRole('tab', { name: 'Logs' }).click();
+
+ await expect(page.locator('[data-testid="container-log-cpu-monitor"]')).toBeVisible();
+ await expect(page.locator('[data-testid="container-log-memory-monitor"]')).toBeVisible();
+ await expect(page.locator('[data-testid="container-log-cpu-monitor"]')).toContainText('N/A');
+ await expect(page.locator('[data-testid="container-log-memory-monitor"]')).toContainText('N/A');
+ });
+
test('should show correct actions based on container state (without changing state)', async ({
page
}) => {
diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.ts
index 4ce8e9797..fe9cad8e3 100644
--- a/tests/spec/project.spec.ts
+++ b/tests/spec/project.spec.ts
@@ -916,7 +916,7 @@ test.describe('Project Detail Page', () => {
if (logsSelected === 'true') {
await expect(page.getByText(/Real-time project logs/i)).toBeVisible();
await expect(page.getByRole('button', { name: /^(Start|Stop)$/i })).toBeVisible();
- await expect(page.getByRole('button', { name: 'Clear', exact: true })).toBeVisible();
+ await expect(page.getByTitle('Refresh')).toBeVisible();
const startButton = page.getByRole('button', {
name: 'Start',
diff --git a/types/container/history.go b/types/container/history.go
new file mode 100644
index 000000000..c49bdc116
--- /dev/null
+++ b/types/container/history.go
@@ -0,0 +1,17 @@
+package container
+
+import dockercontainer "github.com/moby/moby/api/types/container"
+
+// StatsHistorySample is a compact history sample for container CPU and memory usage.
+type StatsHistorySample struct {
+ CPUTenths uint16 `json:"cpuTenths"`
+ MemoryTenths uint16 `json:"memoryTenths"`
+ MemoryUsageBytes uint64 `json:"memoryUsageBytes"`
+}
+
+// StatsStreamPayload is the container stats websocket payload.
+type StatsStreamPayload struct {
+ dockercontainer.StatsResponse
+ StatsHistory []StatsHistorySample `json:"statsHistory,omitempty"`
+ CurrentHistorySample StatsHistorySample `json:"currentHistorySample"`
+}