Skip to content

Commit 1474dac

Browse files
authored
Merge pull request #29 from rhyek/feat/nested-json-logs
List nested JSON log values field by field
2 parents 84959e5 + e37725a commit 1474dac

7 files changed

Lines changed: 220 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# Changelog
22

3+
## 0.11.1
4+
5+
### Features
6+
7+
- **JSON logs list nested objects and arrays field by field, and nested stack traces keep their
8+
line breaks.** See [docs/guide/logs.md](docs/guide/logs.md#json-logs-are-formatted-for-you).
9+
310
## 0.11.0
411

512
### Features

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ their environment, and shows it all in one place.
1717
services it needs come with it, started in order and held until they are healthy.
1818
- **A terminal UI.** One combined, filterable log, with each service's state and memory in
1919
the footer. Drive it with the keyboard or the mouse.
20+
- **Readable JSON logs.** Log JSON in every environment: each line is shown as a colored
21+
`[LEVEL] message` with its fields listed below it, nested ones and stack traces included.
2022
- **Built for coding agents.** A headless mode, a localhost control API, an installable skill
2123
and `llms.txt`.
2224
- **Infra included.** Point it at your `docker-compose.yaml`: databases and brokers come up,

‎docs/config/logs.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ The log file always has timestamps.
4141
Called with each line of the service's output. It returns the text to show.
4242

4343
The default passes plain text through and renders a JSON log as `[LEVEL] message`, with the
44-
remaining fields indented below. Replace it with one of the `logging` helpers to adjust that
44+
remaining fields indented below, nested ones included: see
45+
[JSON logs are formatted for you](../guide/logs.md#json-logs-are-formatted-for-you). Replace it with one of the `logging` helpers to adjust that
4546
rendering, or with [a function of your own](#writing-your-own) for any other format.
4647

4748
## The `logging` helpers
@@ -85,6 +86,8 @@ logging.formatter((log) => ({
8586
}));
8687
```
8788

89+
`custom` names top-level fields. A nested field prints under its parent, as it is in the log.
90+
8891
### Levels
8992

9093
A string level is matched to `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR` or `FATAL`, ignoring

‎docs/guide/logs.md‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,10 @@ shown.
2323

2424
## JSON logs are formatted for you
2525

26-
Plain text passes through untouched. A line that is a JSON log (Go's `slog`, pino, winston)
27-
is shown as a colored `[LEVEL] message`, with its other fields listed below:
26+
Log JSON in every environment and stackctl makes it readable: a service needs no `NODE_ENV`
27+
branch in its logger and no pretty-printer in development. A line that is a JSON log (Go's
28+
`slog`, pino, bunyan, winston, zap) is shown as a colored `[LEVEL] message`, with its other
29+
fields listed below:
2830

2931
```
3032
{"time":"2026-07-13T13:53:32Z","level":"INFO","msg":"listening","port":3002}
@@ -36,8 +38,30 @@ is shown as a colored `[LEVEL] message`, with its other fields listed below:
3638
port: 3002
3739
```
3840

39-
So a service can log JSON in every environment, with no `NODE_ENV` branch in its logger. There
40-
is nothing to configure. To map numeric levels, hide a field or format non-JSON output, see
41+
Nested objects are listed the same way, one level deeper, and a multi-line string such as a
42+
stack trace keeps its line breaks:
43+
44+
```
45+
{"level":"ERROR","msg":"query failed","err":{"type":"Error","message":"connection refused","stack":"Error: connection refused\n at connect (src/db.ts:12:9)\n at query (src/db.ts:30:5)"},"table":"users","tags":["db","retry"]}
46+
```
47+
48+
```
49+
[ERROR] query failed
50+
err:
51+
type: Error
52+
message: connection refused
53+
stack: Error: connection refused
54+
at connect (src/db.ts:12:9)
55+
at query (src/db.ts:30:5)
56+
table: users
57+
tags: ["db","retry"]
58+
```
59+
60+
- **Plain text passes through untouched**, as the service printed it.
61+
- **An array of plain values stays on one line.** An array of objects is listed as `- ` items.
62+
- **The whole log is one entry**, so a filter that matches any of its lines shows all of them.
63+
64+
There is nothing to configure. To map numeric levels, hide a field or format non-JSON output, see
4165
[the `logs` options](../config/logs.md).
4266

4367
## Timestamps

‎docs/index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ features:
5656
link: /config/config-file
5757
- icon: 🖥️
5858
title: A terminal UI you'll keep open
59-
details: "One combined, filterable log, with each service's state and memory in the footer. Drive it with the keyboard or the mouse: click a service, a key hint or a script, and drag to copy."
59+
details: "One combined, filterable log, JSON logs formatted for reading, and each service's state and memory in the footer. Drive it with the keyboard or the mouse: click a service, a key hint or a script, and drag to copy."
6060
link: /guide/terminal-ui
6161
- icon: 🤖
6262
title: Built for coding agents

‎packages/stackctl/src/log-formatter.spec.ts‎

Lines changed: 121 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ describe('createFormatter', () => {
5454
);
5555
});
5656

57-
test('preserves property order and renders non-string values as JSON', () => {
58-
expect(f('{"level":"INFO","msg":"hi","count":3,"meta":{"a":1}}')).toBe(
59-
'[INFO] hi\n count: 3\n meta: {"a":1}',
57+
test('preserves property order and renders scalar values as JSON', () => {
58+
expect(f('{"level":"INFO","msg":"hi","count":3,"ok":true,"none":null}')).toBe(
59+
'[INFO] hi\n count: 3\n ok: true\n none: null',
6060
);
6161
});
6262

@@ -235,6 +235,115 @@ describe('createFormatter', () => {
235235
});
236236
});
237237

238+
describe('nested values', () => {
239+
const f = fmt();
240+
241+
test('expands a nested object into indented properties', () => {
242+
const line = JSON.stringify({
243+
level: 'INFO',
244+
msg: 'request',
245+
req: { method: 'GET', url: '/users', query: { page: 2 } },
246+
});
247+
expect(f(line)).toBe(
248+
'[INFO] request\n' +
249+
' req:\n' +
250+
' method: GET\n' +
251+
' url: /users\n' +
252+
' query:\n' +
253+
' page: 2',
254+
);
255+
});
256+
257+
test("keeps a nested stack trace's line breaks, aligned under its value", () => {
258+
const line = JSON.stringify({
259+
level: 'ERROR',
260+
msg: 'call failed',
261+
err: { type: 'Error', message: 'boom', stack: 'Error: boom\n at charge (a.ts:42:11)' },
262+
});
263+
expect(f(line)).toBe(
264+
'[ERROR] call failed\n' +
265+
' err:\n' +
266+
' type: Error\n' +
267+
' message: boom\n' +
268+
' stack: Error: boom\n' +
269+
' at charge (a.ts:42:11)',
270+
);
271+
});
272+
273+
test('keeps an array of scalars, and empty objects and arrays, inline', () => {
274+
const line = JSON.stringify({
275+
level: 'INFO',
276+
msg: 'm',
277+
tags: ['a', 'b'],
278+
ids: [1, 2],
279+
meta: {},
280+
list: [],
281+
});
282+
expect(f(line)).toBe('[INFO] m\n tags: ["a","b"]\n ids: [1,2]\n meta: {}\n list: []');
283+
});
284+
285+
test('lists an array of objects as `- ` items', () => {
286+
const line = JSON.stringify({
287+
level: 'INFO',
288+
msg: 'm',
289+
rows: [{ id: 1, name: 'a' }, { id: 2 }],
290+
});
291+
expect(f(line)).toBe(
292+
['[INFO] m', ' rows:', ' - id: 1', ' name: a', ' - id: 2'].join('\n'),
293+
);
294+
});
295+
296+
test('lists a mixed array item by item, a multi-line string aligned past its dash', () => {
297+
const line = JSON.stringify({
298+
level: 'INFO',
299+
msg: 'm',
300+
items: ['x', 'one\ntwo', { k: 'v' }, [1, 2]],
301+
});
302+
expect(f(line)).toBe(
303+
'[INFO] m\n' +
304+
' items:\n' +
305+
' - x\n' +
306+
' - one\n' +
307+
' two\n' +
308+
' - k: v\n' +
309+
' - [1,2]',
310+
);
311+
});
312+
313+
test('expands an array nested in an array', () => {
314+
const line = JSON.stringify({ level: 'INFO', msg: 'm', grid: [[{ a: 1 }]] });
315+
expect(f(line)).toBe('[INFO] m\n grid:\n - - a: 1');
316+
});
317+
318+
test('expands a cause chain at every depth', () => {
319+
const line = JSON.stringify({
320+
level: 'ERROR',
321+
msg: 'm',
322+
err: { message: 'outer', cause: { message: 'inner', stack: 'Error: inner\n at x' } },
323+
});
324+
expect(f(line)).toBe(
325+
'[ERROR] m\n' +
326+
' err:\n' +
327+
' message: outer\n' +
328+
' cause:\n' +
329+
' message: inner\n' +
330+
' stack: Error: inner\n' +
331+
' at x',
332+
);
333+
});
334+
335+
test('renames and hides only top-level fields; nested keys print as they are', () => {
336+
const f2 = fmt({ fields: { custom: { error: 'err', time: { show: false } } } });
337+
const line = JSON.stringify({
338+
level: 'INFO',
339+
msg: 'm',
340+
time: 1,
341+
err: { time: 2 },
342+
});
343+
expect(f2(line)).toBe('[INFO] m\n error:\n time: 2');
344+
});
345+
});
346+
238347
describe('logging.nodejs.pino.formatter', () => {
239348
test('maps pino numeric levels to canonical levels', () => {
240349
const f2 = (line: string) => stripAnsi(logging.nodejs.pino.formatter()(line));
@@ -272,5 +381,14 @@ describe('createFormatter', () => {
272381
`${chalk.green('[INFO]')} hi\n ${chalk.gray('count:')} 1`,
273382
);
274383
});
384+
385+
test('colors nested keys and array dashes like top-level keys', () => {
386+
expect(createFormatter()('{"level":"info","msg":"hi","a":{"b":[{"c":1}]}}')).toBe(
387+
`${chalk.green('[INFO]')} hi\n` +
388+
` ${chalk.gray('a:')}\n` +
389+
` ${chalk.gray('b:')}\n` +
390+
` ${chalk.gray('-')} ${chalk.gray('c:')} 1`,
391+
);
392+
});
275393
});
276394
});

‎packages/stackctl/src/log-formatter.ts‎

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
// (override per service with `logs.formatter`). Each output line is parsed as JSON; non-JSON lines
44
// (and JSON that isn't an object with a recognizable level/message) are returned untouched. A
55
// recognized log renders as a `[LEVEL] message` header — the `[LEVEL]` colored by severity — with
6-
// the remaining properties listed, indented, on the lines below. stackctl splits that multi-line
6+
// the remaining properties listed, indented, on the lines below; a nested object or array is
7+
// expanded the same way, one level deeper at each depth. stackctl splits that multi-line
78
// result into separate log lines and groups the indented ones with the header as continuations.
89

910
import chalk from 'chalk';
@@ -163,11 +164,64 @@ export const winstonLevels: Record<string, string> = {
163164
silly: 'TRACE',
164165
};
165166

166-
/** Render a JSON value for display: strings as-is, everything else via `JSON.stringify`. */
167+
/** Render a JSON value on one line: strings as-is, everything else via `JSON.stringify`. */
167168
function renderValue(value: unknown): string {
168169
return typeof value === 'string' ? value : JSON.stringify(value);
169170
}
170171

172+
const isScalar = (value: unknown) => value === null || typeof value !== 'object';
173+
174+
/**
175+
* Whether a value prints on its key's own line: a scalar (a multi-line string continues below
176+
* it), an empty object or array, and an array of scalars none of which is a multi-line string.
177+
* Anything else is expanded on the lines below.
178+
*/
179+
function isInline(value: unknown): boolean {
180+
if (Array.isArray(value)) {
181+
return value.every((v) => isScalar(v) && !(typeof v === 'string' && v.includes('\n')));
182+
}
183+
return isScalar(value) || Object.keys(value as object).length === 0;
184+
}
185+
186+
/**
187+
* The lines of one `name: value` property at `indent`. An inline value follows the key, its
188+
* continuation lines aligned under it past the `name: ` gutter (measured on the plain name, since
189+
* the printed one carries color codes). A nested object or array goes on the lines below, one
190+
* level deeper: an object as properties, an array as `- ` items.
191+
*/
192+
function propertyLines(name: string, value: unknown, indent: string): string[] {
193+
const key = `${indent}${PROPERTY_KEY_COLOR(`${name}:`)}`;
194+
if (isInline(value)) {
195+
const gutter = indent.length + `${name}: `.length;
196+
return [`${key} ${indentContinuationLines(renderValue(value), gutter)}`];
197+
}
198+
return [key, ...nestedLines(value, indent + PROPERTY_INDENT)];
199+
}
200+
201+
/** The lines of a nested object (its properties) or array (its items), at `indent`. */
202+
function nestedLines(value: unknown, indent: string): string[] {
203+
if (Array.isArray(value)) {
204+
return value.flatMap((item) => itemLines(item, indent));
205+
}
206+
return Object.entries(value as Record<string, unknown>).flatMap(([k, v]) =>
207+
propertyLines(k, v, indent),
208+
);
209+
}
210+
211+
/**
212+
* The lines of one array item at `indent`: `- ` and the value. A nested item is laid out one level
213+
* deeper, and its first line then takes the dash in place of its indent, as YAML writes it.
214+
*/
215+
function itemLines(item: unknown, indent: string): string[] {
216+
const dash = `${indent}${PROPERTY_KEY_COLOR('-')} `;
217+
if (isInline(item)) {
218+
return [`${dash}${indentContinuationLines(renderValue(item), indent.length + 2)}`];
219+
}
220+
const deeper = indent + PROPERTY_INDENT;
221+
const [first = '', ...rest] = nestedLines(item, deeper);
222+
return [dash + first.slice(deeper.length), ...rest];
223+
}
224+
171225
/**
172226
* Indent the continuation lines of a multi-line rendered value by `width`, so they line up under
173227
* where the value starts instead of falling flush-left. This is also what keeps a multi-line entry
@@ -299,12 +353,7 @@ export function createFormatter(config: FormatterConfigInput = {}): (line: strin
299353
if (custom && !custom.show) {
300354
continue;
301355
} // hidden
302-
const name = custom ? custom.display : key;
303-
// Continuation lines line up under the value, past the ` name: ` gutter — measured on the
304-
// plain name, since the printed one carries color codes.
305-
const gutter = PROPERTY_INDENT.length + `${name}: `.length;
306-
const rendered = indentContinuationLines(renderValue(value), gutter);
307-
out.push(`${PROPERTY_INDENT}${PROPERTY_KEY_COLOR(`${name}:`)} ${rendered}`);
356+
out.push(...propertyLines(custom ? custom.display : key, value, PROPERTY_INDENT));
308357
}
309358
return out.join('\n');
310359
};

0 commit comments

Comments
 (0)