feat: show container name in structured log output (#1452)

* feat: show container name in structured log output

Prepend a normalized container name prefix to each line in
ComposeService.streamLogs() so both the structured log viewer
and the raw terminal identify which container produced each entry.

- Backend: prepend displayName (normalized via normalizeContainerName)
  before LogFormatter.process() in sendOutput and flushBuffer.
- LogFormatter: refactor process() to handle both prefix-first and
  timestamp-first input orders via a while-loop; widen PREFIX_REGEX
  to accept dotted service names.
- Frontend: add containerName to LogRow, extract prefix in parseLine,
  render as an inline mono chip in the message column, and include
  the name in downloaded logs (omitting the bracket prefix when null).
- Tests: 14 new tests across log-formatter, compose-service streamLogs,
  and StructuredLogViewer chip rendering + download formatting.

* fix: guard LogFormatter loop to at most one prefix and one timestamp

The while-loop refactored for order-agnostic prefix/timestamp
parsing could continue matching beyond the intended single prefix
and timestamp. A log line like "redis | 2024-...Z api | started"
would falsely colorize "api |" as a second container prefix in
raw terminal output.

Add prefixFound/timestampFound boolean guards so the loop stops
after one prefix and one timestamp, regardless of input order.

* feat: per-service color alternation for log container chips

Add an Appearance setting that lets users switch between unified
cyan and per-service label-token colors for the container name chips
in the structured log viewer.

- Extract HUE_VARS and hashLabel() from NodeLabelPill into a shared
  utility at frontend/src/lib/label-colors.ts.
- Add useLogChipColorMode hook (browser-local localStorage,
  sencho.log-chip-color-mode key, unified by default).
- Add SegmentedControl in Settings > Appearance > Display.
- Apply inline label-token styles via style attribute in per-service
  mode; keep current text-brand/80 bg-brand/10 classes in unified mode.
- 14 new tests across label-colors, hook, and viewer chip rendering.
This commit is contained in:
Anso
2026-06-25 14:13:38 -04:00
committed by GitHub
parent ba1be3cc4e
commit f1f64ec7f6
12 changed files with 646 additions and 77 deletions
+127 -1
View File
@@ -111,7 +111,7 @@ vi.mock('../services/FileSystemService', () => ({
}));
vi.mock('../services/LogFormatter', () => ({
LogFormatter: { formatLine: (line: string) => line },
LogFormatter: { process: (line: string) => line },
}));
// runCommand and the deploy/update paths route through authoredComposeArgs, which
@@ -1056,3 +1056,129 @@ describe('ComposeService - idle-output stall backstop', () => {
expect(getComposeRollbackInfo(error)).toMatchObject({ attempted: true });
});
});
// ── streamLogs ─────────────────────────────────────────────────────────
describe('ComposeService - streamLogs', () => {
it('emits a normalized container name prefix for each container', async () => {
mockGetContainersByStack.mockResolvedValue([
{ Names: ['/mystack-redis-1'], State: 'running', Id: 'abc123' },
{ Names: ['/mystack-api-1'], State: 'running', Id: 'def456' },
]);
const ws = createMockWs();
const svc = ComposeService.getInstance(1);
const proc1 = createMockProcess();
const proc2 = createMockProcess();
mockSpawn
.mockReturnValueOnce(proc1)
.mockReturnValueOnce(proc2);
svc.streamLogs('mystack', ws);
await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalledTimes(2));
// Emit stdout from each container.
proc1.stdout.emit('data', Buffer.from('2024-01-01T00:00:00Z redis log line\n'));
proc2.stdout.emit('data', Buffer.from('2024-01-01T00:00:01Z api response\n'));
const calls = (ws.send as ReturnType<typeof vi.fn>).mock.calls as string[][];
const sentLines = calls.flatMap(c => c[0].split('\r\n')).filter(Boolean);
expect(sentLines).toContain('redis | 2024-01-01T00:00:00Z redis log line');
expect(sentLines).toContain('api | 2024-01-01T00:00:01Z api response');
});
it('prefixes flushBuffer trailing line on child close', async () => {
mockGetContainersByStack.mockResolvedValue([
{ Names: ['/mystack-web-1'], State: 'running', Id: 'ghi789' },
]);
const ws = createMockWs();
const svc = ComposeService.getInstance(1);
const proc = createMockProcess();
mockSpawn.mockReturnValue(proc);
svc.streamLogs('mystack', ws);
await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalled());
// Emit a line without a trailing newline, then close.
proc.stdout.emit('data', Buffer.from('trailing content'));
proc.emit('close', 0);
const calls = (ws.send as ReturnType<typeof vi.fn>).mock.calls as string[][];
const sentLines = calls.flatMap(c => c[0].split('\r\n')).filter(Boolean);
expect(sentLines).toContain('web | trailing content');
});
it('joins chunk-split lines and prefixes once', async () => {
mockGetContainersByStack.mockResolvedValue([
{ Names: ['/mystack-db-1'], State: 'running', Id: 'jkl012' },
]);
const ws = createMockWs();
const svc = ComposeService.getInstance(1);
const proc = createMockProcess();
mockSpawn.mockReturnValue(proc);
svc.streamLogs('mystack', ws);
await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalled());
// Split a single line across two data events.
proc.stdout.emit('data', Buffer.from('2024-01-01T00:00:00Z partial '));
proc.stdout.emit('data', Buffer.from('end of line\n'));
const calls = (ws.send as ReturnType<typeof vi.fn>).mock.calls as string[][];
const sentLines = calls.flatMap(c => c[0].split('\r\n')).filter(Boolean);
expect(sentLines).toContain('db | 2024-01-01T00:00:00Z partial end of line');
});
it('normalizes dotted container names', async () => {
mockGetContainersByStack.mockResolvedValue([
{ Names: ['/mystack-api.v1-1'], State: 'running', Id: 'mno345' },
]);
const ws = createMockWs();
const svc = ComposeService.getInstance(1);
const proc = createMockProcess();
mockSpawn.mockReturnValue(proc);
svc.streamLogs('mystack', ws);
await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalled());
proc.stdout.emit('data', Buffer.from('2024-01-01T00:00:00Z started\n'));
const calls = (ws.send as ReturnType<typeof vi.fn>).mock.calls as string[][];
const sentLines = calls.flatMap(c => c[0].split('\r\n')).filter(Boolean);
// normalizeContainerName strips stack prefix and -1 replica suffix, leaving 'api.v1'.
expect(sentLines).toContain('api.v1 | 2024-01-01T00:00:00Z started');
});
it('passes raw container name to docker logs, not normalized name', async () => {
mockGetContainersByStack.mockResolvedValue([
{ Names: ['/mystack-redis-1'], State: 'running', Id: 'pqr678' },
]);
const ws = createMockWs();
const svc = ComposeService.getInstance(1);
const proc = createMockProcess();
mockSpawn.mockReturnValue(proc);
svc.streamLogs('mystack', ws);
await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalled());
// Verify that docker logs uses the raw name, not the normalized one.
expect(mockSpawn).toHaveBeenCalledWith(
'docker',
['logs', '-f', '-t', '--tail', '100', 'mystack-redis-1'],
expect.anything(),
);
});
});
@@ -0,0 +1,67 @@
import { describe, it, expect } from 'vitest';
import { LogFormatter } from '../services/LogFormatter';
const CYAN = '\x1b[36m';
const GRAY = '\x1b[90m';
const RESET = '\x1b[0m';
const WHITE = '\x1b[37m';
describe('LogFormatter.process', () => {
it('colorizes prefix and timestamp when prefix comes first', () => {
const result = LogFormatter.process('redis | 2024-01-01T00:00:00Z started');
expect(result).toContain(`${CYAN}redis${WHITE}${RESET} | `);
expect(result).toContain(`${GRAY}2024-01-01T00:00:00Z ${RESET}`);
});
it('colorizes timestamp and prefix when timestamp comes first (legacy order)', () => {
const result = LogFormatter.process('2024-01-01T00:00:00Z redis | started');
expect(result).toContain(`${GRAY}2024-01-01T00:00:00Z ${RESET}`);
expect(result).toContain(`${CYAN}redis${WHITE}${RESET} | `);
});
it('colorizes timestamp only when no prefix is present (backward compat)', () => {
const result = LogFormatter.process('2024-01-01T00:00:00Z started');
expect(result).toContain(`${GRAY}2024-01-01T00:00:00Z ${RESET}`);
expect(result).not.toContain(CYAN);
});
it('colorizes dotted container names', () => {
const result = LogFormatter.process('api.v1 | 2024-01-01T00:00:00Z started');
expect(result).toContain(`${CYAN}api.v1${WHITE}${RESET} | `);
expect(result).toContain(`${GRAY}2024-01-01T00:00:00Z ${RESET}`);
});
it('colorizes container names with underscores', () => {
const result = LogFormatter.process('my-service_1 | 2024-01-01T00:00:00Z started');
expect(result).toContain(`${CYAN}my-service_1${WHITE}${RESET} | `);
expect(result).toContain(`${GRAY}2024-01-01T00:00:00Z ${RESET}`);
});
it('handles timestamp with offset notation', () => {
const result = LogFormatter.process('redis | 2024-01-01T00:00:00+05:00 started');
expect(result).toContain(`${CYAN}redis${WHITE}${RESET} | `);
expect(result).toContain(`${GRAY}2024-01-01T00:00:00+05:00 ${RESET}`);
});
it('returns empty string unchanged', () => {
expect(LogFormatter.process('')).toBe('');
});
it('returns whitespace-only string unchanged', () => {
expect(LogFormatter.process(' ')).toBe(' ');
});
it('handles bare message with no prefix or timestamp', () => {
const result = LogFormatter.process('just a plain message');
expect(result).toBe('just a plain message');
});
it('does not colorize a second "word | " in the message body as a prefix', () => {
const result = LogFormatter.process('redis | 2024-01-01T00:00:00Z api | started');
// The first "redis | " is the genuine container prefix.
expect(result).toContain(`${CYAN}redis${WHITE}${RESET} | `);
// The "api | " in the body must not be colorized as a second prefix.
const afterPrefix = result.split(' | ').slice(1).join(' | ');
expect(afterPrefix).not.toContain(CYAN);
});
});
+6 -4
View File
@@ -16,6 +16,7 @@ import { deriveStackExposure } from './preflight/exposure';
import { isDebugEnabled } from '../utils/debug';
import { getErrorMessage } from '../utils/errors';
import { normalizeContainerName } from '../utils/log-parsing';
import { describeSpawnError } from '../utils/spawnErrors';
import { isPathWithinBase, isValidStackName } from '../utils/validation';
import { authoredComposeFileArgs, authoredComposeEnvFileArgs } from '../utils/authoredComposeArgs';
@@ -553,7 +554,8 @@ export class ComposeService {
};
for (const container of containersToLog) {
const containerName = container.Names?.[0]?.replace(/^\//, '') || container.Id;
const rawName = container.Names?.[0]?.replace(/^\//, '') || container.Id;
const displayName = normalizeContainerName(rawName, stackName);
activeProcesses++;
let lineBuffer = '';
@@ -563,19 +565,19 @@ export class ComposeService {
const lines = lineBuffer.split(/\r?\n/);
lineBuffer = lines.pop() || '';
for (const line of lines) {
ws.send(LogFormatter.process(line) + '\r\n');
ws.send(LogFormatter.process(`${displayName} | ${line}`) + '\r\n');
}
}
};
const flushBuffer = () => {
if (lineBuffer && ws.readyState === WebSocket.OPEN) {
ws.send(LogFormatter.process(lineBuffer) + '\r\n');
ws.send(LogFormatter.process(`${displayName} | ${lineBuffer}`) + '\r\n');
lineBuffer = '';
}
};
const child = spawn('docker', ['logs', '-f', '-t', '--tail', '100', containerName], {
const child = spawn('docker', ['logs', '-f', '-t', '--tail', '100', rawName], {
env: {
...process.env,
PATH: process.env.PATH || '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
+36 -19
View File
@@ -13,7 +13,7 @@ export class LogFormatter {
private static readonly TIMESTAMP_REGEX = /^(\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?\s*)/;
// Matches docker-compose style prefix like "container-name | " or "db-1 | "
private static readonly PREFIX_REGEX = /^([a-zA-Z0-9_-]+)(?:\s+\|\s+)/;
private static readonly PREFIX_REGEX = /^([a-zA-Z0-9_.-]+)(?:\s+\|\s+)/;
// Level regexes (case insensitive for matching, but we check raw string for precise targeting if needed)
private static readonly ERROR_REGEX = /\b(ERROR|ERR|Exception|Fatal)\b/i;
@@ -26,26 +26,43 @@ export class LogFormatter {
let processedLine = line;
let formatAccumulator = '';
// 1. Process Timestamp
const tsMatch = processedLine.match(LogFormatter.TIMESTAMP_REGEX);
if (tsMatch) {
const ts = tsMatch[1];
formatAccumulator += `${LogFormatter.GRAY}${ts}${LogFormatter.RESET}`;
processedLine = processedLine.slice(ts.length);
// 1. Process at most one container-name prefix and one Docker
// timestamp in arrival order. Each regex is anchored at ^ and
// strips its match from the remainder. The prefixFound /
// timestampFound guards prevent false matches on legitimate
// log bodies that happen to contain "word | " later in the line.
let changed = true;
let prefixFound = false;
let timestampFound = false;
while (changed) {
changed = false;
if (!prefixFound) {
const prefixMatch = processedLine.match(LogFormatter.PREFIX_REGEX);
if (prefixMatch) {
const pfxMatchStr = prefixMatch[0]; // e.g. "redis | "
const name = prefixMatch[1];
const restOfPrefix = pfxMatchStr.slice(name.length); // e.g. " | "
formatAccumulator += `${LogFormatter.CYAN}${name}${LogFormatter.WHITE}${LogFormatter.RESET}${restOfPrefix}`;
processedLine = processedLine.slice(pfxMatchStr.length);
changed = true;
prefixFound = true;
}
}
if (!timestampFound) {
const tsMatch = processedLine.match(LogFormatter.TIMESTAMP_REGEX);
if (tsMatch) {
const ts = tsMatch[1];
formatAccumulator += `${LogFormatter.GRAY}${ts}${LogFormatter.RESET}`;
processedLine = processedLine.slice(ts.length);
changed = true;
timestampFound = true;
}
}
}
// 2. Process Prefix
const prefixMatch = processedLine.match(LogFormatter.PREFIX_REGEX);
if (prefixMatch) {
const pfxMatchStr = prefixMatch[0]; // e.g. "container-name | "
const name = prefixMatch[1];
const restOfPrefix = pfxMatchStr.slice(name.length); // e.g. " | "
formatAccumulator += `${LogFormatter.CYAN}${name}${LogFormatter.WHITE}${LogFormatter.RESET}${restOfPrefix}`;
processedLine = processedLine.slice(pfxMatchStr.length);
}
// 3. Process Levels & JSON
// 2. Process Levels & JSON
const trimmedLine = processedLine.trim();
// Fast JSON Check (Starts with { and ends with })