Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): clean up the `ok start` terminal experience (#1719)

mike-inkeep7ec66897e70a
diff --git a/.changeset/okstart-terminal-ux.md b/.changeset/okstart-terminal-ux.md
new file mode 100644
index 000000000..f9396b9d7
--- /dev/null
+++ b/.changeset/okstart-terminal-ux.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+`ok start` now has a clean, legible terminal. Diagnostic `INFO` logs are routed to the on-disk log file (still captured for bug reports) instead of flooding stdout, so the startup banner — Editor + API URLs plus a "Next steps" hint — is front and center. The skill/MCP/launch-json reclaim sweeps no longer print routine JSON to the terminal (only genuine failures surface), and invalid frontmatter `tags` entries (e.g. comma-joined Obsidian-style values) are dropped silently instead of warning once per file. To restore the full log stream, set `LOG_LEVEL=info` or pass `--log-level <level>` (which now takes effect — previously it was parsed but ignored).
+
+Two reliability fixes ride along: the HEAD watcher falls back to chokidar when `@parcel/watcher` is unavailable (packaged builds ship without the native addon), so git branch-switch detection keeps working instead of silently degrading; and pressing Ctrl+C now prints an immediate "stopping…" notice explaining that pending changes are being saved and the server lock released.
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 24ff5871b..74d475279 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -67,7 +67,11 @@ program
.usage('[options] [file | command]')
.version(buildVersionNotice(PACKAGE_VERSION))
.option('--cwd <path>', 'Working directory')
- .option('--log-level <level>', 'Log level', 'info')
+ .option(
+ '--log-level <level>',
+ 'Log level: silent, error, warn, info (default), debug, trace',
+ 'info',
+ )
.option('--no-color', 'Disable color output')
.option('--color', 'Force color output')
.hook('preAction', (thisCommand) => {
@@ -76,6 +80,13 @@ program
if (cwd !== undefined) {
process.chdir(cwd);
}
+
+ if (program.getOptionValueSource('logLevel') === 'cli') {
+ const level = String(program.opts().logLevel);
+ process.env.LOG_LEVEL = level;
+ process.env.OK_CONSOLE_LEVEL = level;
+ }
+
const { config } = loadConfig(cwd);
resolvedConfig = config;
diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.ts
index 7ba9d884e..e3896ba94 100644
--- a/packages/cli/src/commands/start.test.ts
+++ b/packages/cli/src/commands/start.test.ts
@@ -17,10 +17,12 @@ import {
connectUiSibling,
decideUiSpawn,
deriveServerProcessTitle,
+ formatShutdownNotice,
isServerLockCollision,
OkDirMissingError,
resolveCollabPort,
resolveHost,
+ resolveStartConsoleLevel,
shouldConnectToExistingServer,
spawnOkUi,
startCommand,
@@ -47,6 +49,37 @@ describe('resolveHost', () => {
});
});
+describe('formatShutdownNotice', () => {
+ test('SIGINT includes the headline, the wait notice, and the force-quit hint', () => {
+ const lines = formatShutdownNotice('SIGINT');
+ expect(lines[0]).toContain('Stopping Open Knowledge');
+ expect(lines.some((l) => l.includes('few seconds'))).toBe(true);
+ expect(lines.some((l) => l.includes('force quit'))).toBe(true);
+ });
+
+ test('SIGTERM omits the force-quit hint (no interactive second-press path)', () => {
+ const lines = formatShutdownNotice('SIGTERM');
+ expect(lines[0]).toContain('Stopping Open Knowledge');
+ expect(lines.some((l) => l.includes('few seconds'))).toBe(true);
+ expect(lines.some((l) => l.includes('force quit'))).toBe(false);
+ });
+});
+
+describe('resolveStartConsoleLevel', () => {
+ test('returns "warn" when no level is pinned (quiet terminal by default)', () => {
+ expect(resolveStartConsoleLevel({})).toBe('warn');
+ });
+
+ test('returns null (leave env untouched) when LOG_LEVEL is set', () => {
+ expect(resolveStartConsoleLevel({ LOG_LEVEL: 'info' })).toBeNull();
+ expect(resolveStartConsoleLevel({ LOG_LEVEL: 'debug' })).toBeNull();
+ });
+
+ test('returns null when OK_CONSOLE_LEVEL is already set', () => {
+ expect(resolveStartConsoleLevel({ OK_CONSOLE_LEVEL: 'info' })).toBeNull();
+ });
+});
+
describe('deriveServerProcessTitle', () => {
test('returns "open-knowledge-server <basename>" for a typical project path', () => {
expect(deriveServerProcessTitle('/Users/alice/projects/my-notes')).toBe(
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index fa0804ff0..703142c41 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -289,11 +289,20 @@ interface BootStartServerOptions {
idleThresholdMs?: number;
uiBindTimeoutMs?: number;
log?: PinoLogger;
- repairMcpConfigsFn?: (opts: { projectDir: string; reclaimDisableEnv: string | null }) => unknown;
- repairLaunchJsonFn?: (opts: { projectDir: string; reclaimDisableEnv: string | null }) => unknown;
+ repairMcpConfigsFn?: (opts: {
+ projectDir: string;
+ reclaimDisableEnv: string | null;
+ logger?: (event: { event: string }) => void;
+ }) => unknown;
+ repairLaunchJsonFn?: (opts: {
+ projectDir: string;
+ reclaimDisableEnv: string | null;
+ logger?: (event: { event: string }) => void;
+ }) => unknown;
repairSkillsFn?: (opts: {
projectDir: string;
reclaimDisableEnv: string | null;
+ logger?: (event: { event: string }) => void;
}) => Promise<unknown> | unknown;
serveContentAssets?: boolean;
reactShellDistDir?: string;
@@ -342,10 +351,17 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
const reclaimDisableEnv = process.env.OK_RECLAIM_DISABLE ?? null;
+ const reclaimEventLogger = (event: { event: string }) => {
+ const name = typeof event.event === 'string' ? event.event : '';
+ if (name.endsWith('-failed') || name.endsWith('-error') || name.endsWith('-missing')) {
+ log.warn({ event }, '[start] reclaim sweep reported a problem');
+ }
+ };
+
try {
const repair =
opts.repairMcpConfigsFn ?? (await import('./repair-mcp-configs.ts')).repairMcpConfigs;
- repair({ projectDir: cwd, reclaimDisableEnv });
+ repair({ projectDir: cwd, reclaimDisableEnv, logger: reclaimEventLogger });
} catch (err) {
log.warn({ err }, '[start] mcp-config repair sweep failed; continuing');
}
@@ -353,14 +369,14 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
try {
const repair =
opts.repairLaunchJsonFn ?? (await import('./repair-launch-json.ts')).repairLaunchJson;
- repair({ projectDir: cwd, reclaimDisableEnv });
+ repair({ projectDir: cwd, reclaimDisableEnv, logger: reclaimEventLogger });
} catch (err) {
log.warn({ err }, '[start] launch.json repair sweep failed; continuing');
}
try {
const repair = opts.repairSkillsFn ?? (await import('./repair-skills.ts')).repairSkills;
- await repair({ projectDir: cwd, reclaimDisableEnv });
+ await repair({ projectDir: cwd, reclaimDisableEnv, logger: reclaimEventLogger });
} catch (err) {
log.warn({ err }, '[start] skill repair sweep failed; continuing');
}
@@ -524,9 +540,31 @@ function parseUiPort(value: string): number {
return port;
}
+export function resolveStartConsoleLevel(env: {
+ OK_CONSOLE_LEVEL?: string | undefined;
+ LOG_LEVEL?: string | undefined;
+}): string | null {
+ if (env.OK_CONSOLE_LEVEL !== undefined || env.LOG_LEVEL !== undefined) return null;
+ return 'warn';
+}
+
+export function formatShutdownNotice(signal: NodeJS.Signals): string[] {
+ const lines = [
+ 'Stopping Open Knowledge…',
+ 'Saving pending changes and releasing the server lock — this can take a few seconds.',
+ ];
+ if (signal === 'SIGINT') {
+ lines.push('Press Ctrl+C again to force quit.');
+ }
+ return lines;
+}
+
export async function runStartCommand(config: Config, opts: StartCommandOptions): Promise<void> {
+ const startConsoleLevel = resolveStartConsoleLevel(process.env);
+ if (startConsoleLevel !== null) process.env.OK_CONSOLE_LEVEL = startConsoleLevel;
+
const { renderBanner } = await import('../ui/banner.ts');
- const { dim, error, warning } = await import('../ui/colors.ts');
+ const { accent, dim, error, warning } = await import('../ui/colors.ts');
const cwd = process.cwd();
const activeConfig = config;
@@ -605,7 +643,11 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)
const shutdown = async (signal: NodeJS.Signals) => {
if (shuttingDown) return;
shuttingDown = true;
- console.log(dim(`\nShutting down (${signal})`));
+ const [headline, ...details] = formatShutdownNotice(signal);
+ console.log(accent(`\n${headline}`));
+ for (const line of details) {
+ console.log(dim(` ${line}`));
+ }
try {
await booted.destroy();
} catch (err) {
@@ -637,6 +679,7 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)
localUrl,
apiUrl: localUrl !== apiUrl ? apiUrl : undefined,
networkUrl,
+ nextSteps: ['Open the Editor URL in your browser to start editing.'],
}),
);
const DEGRADED_IMPACTS: Record<string, string> = {
diff --git a/packages/cli/src/ui/banner.test.ts b/packages/cli/src/ui/banner.test.ts
index ce64dd4c8..d4aca7821 100644
--- a/packages/cli/src/ui/banner.test.ts
+++ b/packages/cli/src/ui/banner.test.ts
@@ -79,6 +79,44 @@ describe('renderBanner', () => {
expect(output).toContain('Ctrl+C');
});
+ test('renders next-steps lines when provided', () => {
+ const output = renderBanner({
+ name: 'open-knowledge',
+ version: VERSION,
+ localUrl: 'http://localhost:3000',
+ nextSteps: ['Open the Editor URL in your browser to start editing.'],
+ });
+ expect(output).toContain('Open the Editor URL in your browser to start editing.');
+ expect(output).toContain('Ctrl+C');
+ });
+
+ test('omits next-steps section when not provided', () => {
+ const output = renderBanner({
+ name: 'open-knowledge',
+ version: VERSION,
+ localUrl: 'http://localhost:3000',
+ });
+ expect(output).not.toContain('Open the Editor URL');
+ });
+
+ test('box lines stay consistent width with next-steps lines', () => {
+ const output = renderBanner({
+ name: 'open-knowledge',
+ version: VERSION,
+ localUrl: 'http://localhost:3000',
+ apiUrl: 'http://localhost:52345',
+ nextSteps: ['Open the Editor URL in your browser to start editing.'],
+ });
+ const stripped = output
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ANSI stripping
+ .replace(/\x1b\[[0-9;]*m/g, '')
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional OSC 8 hyperlink stripping
+ .replace(/\x1b\]8;;[^\x07]*\x07/g, '');
+ const lines = stripped.split('\n').filter((l) => l.trim().length > 0);
+ const uniqueWidths = [...new Set(lines.map((l) => l.length))];
+ expect(uniqueWidths).toHaveLength(1);
+ });
+
test('uses box-drawing characters', () => {
const output = renderBanner({
name: 'open-knowledge',
diff --git a/packages/cli/src/ui/banner.ts b/packages/cli/src/ui/banner.ts
index d65f3938c..c3a2b53ba 100644
--- a/packages/cli/src/ui/banner.ts
+++ b/packages/cli/src/ui/banner.ts
@@ -9,6 +9,7 @@ interface BannerOptions {
localUrl: string;
networkUrl?: string;
apiUrl?: string;
+ nextSteps?: string[];
}
export function renderBanner(opts: BannerOptions): string {
@@ -41,6 +42,13 @@ export function renderBanner(opts: BannerOptions): string {
});
}
+ if (opts.nextSteps && opts.nextSteps.length > 0) {
+ lines.push({ plain: '', colored: '' });
+ for (const step of opts.nextSteps) {
+ lines.push({ plain: step, colored: dim(step) });
+ }
+ }
+
lines.push({ plain: '', colored: '' });
const hint = 'Press Ctrl+C to stop';
lines.push({ plain: hint, colored: dim(hint) });
diff --git a/packages/core/src/frontmatter/tags.test.ts b/packages/core/src/frontmatter/tags.test.ts
index 5a78511a1..fe9aef757 100644
--- a/packages/core/src/frontmatter/tags.test.ts
+++ b/packages/core/src/frontmatter/tags.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, spyOn, test } from 'bun:test';
+import { describe, expect, test } from 'bun:test';
import {
extractFrontmatterTags,
FRONTMATTER_TAG_GRAMMAR_HINT,
@@ -53,15 +53,9 @@ describe('extractFrontmatterTags', () => {
]);
});
- test('drops invalid entries with a warning rather than failing the whole list', () => {
- const warn = spyOn(console, 'warn').mockImplementation(mock(() => {}));
- try {
- const out = extractFrontmatterTags('tags: [valid, "with space", "123digit", another]\n');
- expect(out).toEqual(['valid', '123digit', 'another']);
- expect(warn).toHaveBeenCalledTimes(1);
- } finally {
- warn.mockRestore();
- }
+ test('drops invalid entries rather than failing the whole list', () => {
+ const out = extractFrontmatterTags('tags: [valid, "with space", "123digit", another]\n');
+ expect(out).toEqual(['valid', '123digit', 'another']);
});
test('coerces non-string scalars and applies the per-entry tag regex', () => {
diff --git a/packages/core/src/frontmatter/tags.ts b/packages/core/src/frontmatter/tags.ts
index c9801f480..764b26739 100644
--- a/packages/core/src/frontmatter/tags.ts
+++ b/packages/core/src/frontmatter/tags.ts
@@ -31,8 +31,6 @@ export function extractFrontmatterTags(yaml: string): string[] {
const stripped = stripLeadingHash(candidate);
if (FRONTMATTER_TAG_VALUE_RE.test(stripped)) {
out.push(stripped);
- } else {
- console.warn(`[frontmatter-tags] dropping invalid tag entry: ${JSON.stringify(candidate)}`);
}
}
return out;
diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.ts
index a4b40258e..753a5c5a4 100644
--- a/packages/server/src/file-watcher.ts
+++ b/packages/server/src/file-watcher.ts
@@ -933,9 +933,9 @@ async function startParcelWatcher(
try {
parcel = await import('@parcel/watcher');
} catch (err) {
- console.warn(
- '[file-watcher] @parcel/watcher import failed:',
- err instanceof Error ? err.message : err,
+ getLogger('file-watcher').debug(
+ { err: err instanceof Error ? err.message : String(err) },
+ '[file-watcher] @parcel/watcher import failed; falling back to chokidar',
);
return null;
}
@@ -985,7 +985,6 @@ async function startChokidarWatcher(
aliasMap: Map<string, string>,
): Promise<AsyncSubscription> {
const { watch } = await import('chokidar');
- console.warn('[file-watcher] @parcel/watcher unavailable, using chokidar fallback');
const watcher = watch(contentDir, {
ignoreInitial: true,
diff --git a/packages/server/src/head-watcher.test.ts b/packages/server/src/head-watcher.test.ts
index 640cc2479..fbd5f676e 100644
--- a/packages/server/src/head-watcher.test.ts
+++ b/packages/server/src/head-watcher.test.ts
@@ -1,10 +1,11 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { execSync } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
-import { readBranchFromHead } from './head-watcher';
+import { readBranchFromHead, startHeadWatcher, watchedGitFile } from './head-watcher';
let tmpDir: string;
@@ -85,3 +86,47 @@ describe('readBranchFromHead', () => {
expect(readBranchFromHead(gitDir)).toBeNull();
});
});
+
+describe('watchedGitFile', () => {
+ test('returns the basename for watched .git ref files', () => {
+ expect(watchedGitFile('/x/.git/HEAD')).toBe('HEAD');
+ expect(watchedGitFile('/x/.git/ORIG_HEAD')).toBe('ORIG_HEAD');
+ expect(watchedGitFile('/x/.git/MERGE_HEAD')).toBe('MERGE_HEAD');
+ expect(watchedGitFile('/x/.git/index.lock')).toBe('index.lock');
+ });
+
+ test('returns null for paths outside the watched set', () => {
+ expect(watchedGitFile('/x/.git/config')).toBeNull();
+ expect(watchedGitFile('/x/.git/objects/ab/cdef')).toBeNull();
+ expect(watchedGitFile('')).toBeNull();
+ });
+});
+
+describe('startHeadWatcher chokidar fallback', () => {
+ test('selects the chokidar backend, reads initial state, and tears down cleanly', async () => {
+ const projectRoot = resolve(tmpDir, 'repo');
+ mkdirSync(projectRoot, { recursive: true });
+ const git = (args: string) => execSync(`git ${args}`, { cwd: projectRoot, stdio: 'ignore' });
+ git('init -q');
+ git('config user.email [email protected]');
+ git('config user.name t');
+ writeFileSync(resolve(projectRoot, 'a.md'), 'hello\n');
+ git('add -A');
+ git('commit -qm init');
+ git('branch -M main'); // normalize branch name across git default-branch configs
+
+ const handle = await startHeadWatcher(
+ projectRoot,
+ () => {},
+ () => {},
+ {
+ forceBackend: 'chokidar',
+ },
+ );
+ try {
+ expect(handle.getLastKnownBranch()).toBe('main');
+ } finally {
+ await handle.unsubscribe();
+ }
+ });
+});
diff --git a/packages/server/src/head-watcher.ts b/packages/server/src/head-watcher.ts
index 315d6350b..b56fe89d3 100644
--- a/packages/server/src/head-watcher.ts
+++ b/packages/server/src/head-watcher.ts
@@ -70,10 +70,67 @@ export function readBranchFromHead(gitDir: string): string | null {
}
}
+type HeadEventDispatch = (rawPath: string) => void;
+
+export function watchedGitFile(rawPath: string): string | null {
+ const fileName = rawPath.split('/').pop() ?? '';
+ return WATCHED_FILES.has(fileName) ? fileName : null;
+}
+
+async function tryStartParcelHeadWatcher(
+ gitDir: string,
+ dispatch: HeadEventDispatch,
+): Promise<(() => Promise<void>) | null> {
+ let parcel: typeof import('@parcel/watcher');
+ try {
+ parcel = await import('@parcel/watcher');
+ } catch (err) {
+ getLogger('head-watcher').debug(
+ { err: err instanceof Error ? err.message : String(err) },
+ '[head-watcher] @parcel/watcher unavailable; falling back to chokidar',
+ );
+ return null;
+ }
+ try {
+ const subscription = await parcel.subscribe(gitDir, (err, events) => {
+ if (err) {
+ getLogger('head-watcher').warn({ err }, '[head-watcher] parcel subscription error');
+ return;
+ }
+ for (const event of events) dispatch(event.path);
+ });
+ return () => subscription.unsubscribe();
+ } catch (err) {
+ getLogger('head-watcher').debug(
+ { err: err instanceof Error ? err.message : String(err) },
+ '[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar',
+ );
+ return null;
+ }
+}
+
+async function startChokidarHeadWatcher(
+ gitDir: string,
+ dispatch: HeadEventDispatch,
+): Promise<() => Promise<void>> {
+ const { watch } = await import('chokidar');
+ const watcher = watch(gitDir, {
+ ignoreInitial: true,
+ depth: 0,
+ followSymlinks: false,
+ });
+ watcher.on('all', (_event, path) => dispatch(path));
+ watcher.on('error', (err) => {
+ getLogger('head-watcher').warn({ err }, '[head-watcher] chokidar watcher error');
+ });
+ return () => watcher.close();
+}
+
export async function startHeadWatcher(
projectRoot: string,
onBatchBegin: OnBatchBegin,
onBatchEnd: OnBatchEnd,
+ opts: { forceBackend?: 'parcel' | 'chokidar' } = {},
): Promise<HeadWatcherHandle> {
const resolvedGitDir = resolveGitDir(projectRoot);
if (!resolvedGitDir) {
@@ -168,44 +225,30 @@ export async function startHeadWatcher(
resetQuietWindow();
}
- let unsubscribeFn: () => Promise<void>;
- let parcel: typeof import('@parcel/watcher');
- try {
- parcel = await import('@parcel/watcher');
- } catch (err) {
- throw new Error(
- `@parcel/watcher unavailable for HEAD watching: ${err instanceof Error ? err.message : err}`,
- );
- }
-
- try {
- const subscription = await parcel.subscribe(gitDir, (err, events) => {
- if (err) {
- console.error('[head-watcher]', err);
- return;
- }
+ const dispatch: HeadEventDispatch = (rawPath) => {
+ const fileName = watchedGitFile(rawPath);
+ if (fileName !== null) void handleGitEvent(fileName);
+ };
- for (const event of events) {
- const fileName = event.path.split('/').pop() ?? '';
- if (WATCHED_FILES.has(fileName)) {
- void handleGitEvent(fileName);
- break;
- }
- }
- });
- unsubscribeFn = () => subscription.unsubscribe();
- } catch (err) {
- throw new Error(
- `@parcel/watcher subscribe failed for HEAD watching: ${
- err instanceof Error ? err.message : err
- }`,
- );
+ let resolvedUnsub: (() => Promise<void>) | null = null;
+ let backend: 'parcel' | 'chokidar' = 'chokidar';
+ if (opts.forceBackend !== 'chokidar') {
+ resolvedUnsub = await tryStartParcelHeadWatcher(gitDir, dispatch);
+ if (resolvedUnsub) backend = 'parcel';
+ }
+ if (!resolvedUnsub) {
+ if (opts.forceBackend === 'parcel') {
+ throw new Error('@parcel/watcher unavailable for HEAD watching (forced backend)');
+ }
+ resolvedUnsub = await startChokidarHeadWatcher(gitDir, dispatch);
+ backend = 'chokidar';
}
+ const unsubscribeFn: () => Promise<void> = resolvedUnsub;
oldHead = readHeadSha(gitDir);
lastKnownBranch = readBranchFromHead(gitDir);
- getLogger('head-watcher').info({ gitDir }, 'watching for HEAD changes');
+ getLogger('head-watcher').info({ gitDir, backend }, 'watching for HEAD changes');
return {
unsubscribe: async () => {
diff --git a/packages/server/src/logger.test.ts b/packages/server/src/logger.test.ts
index fcf4e73b3..541f27f3a 100644
--- a/packages/server/src/logger.test.ts
+++ b/packages/server/src/logger.test.ts
@@ -213,6 +213,50 @@ describe('Logger', () => {
expect(secondPrev.msg).toBe('second-large-record');
});
+ it('configure(pinoConfig) reconfigures already-cached loggers in place (captured refs gain the sink)', async () => {
+ const captured = loggerFactory.getLogger('captured-early');
+ captured.info({}, 'before-configure');
+ await captured.flushFileSink();
+ expect(existsSync(logsCurrentPath(tmp))).toBe(false);
+
+ loggerFactory.configure({
+ pinoConfig: {
+ options: { level: 'info' },
+ fileSink: { projectDir: tmp, maxBytes: 1_000_000 },
+ },
+ });
+
+ expect(loggerFactory.getLogger('captured-early')).toBe(captured);
+ captured.info({}, 'after-configure');
+ await captured.flushFileSink();
+
+ const records = await readLogLinesWhen(logsCurrentPath(tmp), 1);
+ expect(records.map((r) => r.msg)).toEqual(['after-configure']);
+ });
+
+ it('OK_CONSOLE_LEVEL raises the stdout stream without flooring the file sink', async () => {
+ const prev = process.env.OK_CONSOLE_LEVEL;
+ process.env.OK_CONSOLE_LEVEL = 'warn';
+ try {
+ const logger = new PinoLogger('test', {
+ options: { level: 'info' },
+ fileSink: { projectDir: tmp, maxBytes: 1_000_000 },
+ });
+ expect(logger.getPinoInstance().level).toBe('info');
+
+ logger.info({}, 'info-to-disk');
+ logger.warn({}, 'warn-to-disk');
+ await logger.flushFileSink();
+
+ const records = await readLogLinesWhen(logsCurrentPath(tmp), 2);
+ expect(records.map((r) => r.msg)).toEqual(['info-to-disk', 'warn-to-disk']);
+ expect(records[0]?.level).toBe(30);
+ } finally {
+ if (prev === undefined) delete process.env.OK_CONSOLE_LEVEL;
+ else process.env.OK_CONSOLE_LEVEL = prev;
+ }
+ });
+
it('omits file destination when fileSink config is absent (no .ok/local/logs created)', async () => {
const logger = new PinoLogger('test', {
options: { level: 'info' },
diff --git a/packages/server/src/logger.ts b/packages/server/src/logger.ts
index f14544c28..a5e0c7f2a 100644
--- a/packages/server/src/logger.ts
+++ b/packages/server/src/logger.ts
@@ -22,6 +22,17 @@ function shouldColorize(): boolean {
return process.stdout.isTTY ?? false;
}
+const VALID_LOG_LEVELS = new Set(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']);
+
+function logLevelRank(level: string): number {
+ if (level === 'silent') return Number.POSITIVE_INFINITY;
+ return pino.levels.values[level] ?? pino.levels.values.info;
+}
+
+function mostVerboseLevel(a: string, b: string): string {
+ return logLevelRank(a) <= logLevelRank(b) ? a : b;
+}
+
export interface PinoLoggerConfig {
options?: LoggerOptions;
transportConfigs?: TransportSingleOptions[];
@@ -69,9 +80,22 @@ export class PinoLogger {
this.pinoInstance = this.buildInstance();
}
+ private resolveStreamLevels(): {
+ fileLevel: string;
+ consoleLevel: string;
+ instanceLevel: string;
+ } {
+ const fileLevel = (this.options.level as string | undefined) ?? 'info';
+ const envConsole = process.env.OK_CONSOLE_LEVEL?.toLowerCase();
+ const consoleLevel = envConsole && VALID_LOG_LEVELS.has(envConsole) ? envConsole : fileLevel;
+ return { fileLevel, consoleLevel, instanceLevel: mostVerboseLevel(fileLevel, consoleLevel) };
+ }
+
private buildInstance(): PinoLoggerInstance {
this.activeFileSink = undefined;
+ const { fileLevel, consoleLevel, instanceLevel } = this.resolveStreamLevels();
+
if (this.transportConfigs.length > 0) {
return pino(this.options, pino.transport({ targets: this.transportConfigs }));
}
@@ -88,17 +112,26 @@ export class PinoLogger {
if (this.fileSinkOpts) {
const fileSink = new PinoFileSink(this.fileSinkOpts);
this.activeFileSink = fileSink;
- return pino(this.options, pino.multistream([{ stream: fileSink }]));
+ return pino(
+ { ...this.options, level: instanceLevel },
+ pino.multistream([{ stream: fileSink, level: fileLevel }]),
+ );
}
- return pino(this.options);
+ return pino({ ...this.options, level: consoleLevel });
}
if (this.fileSinkOpts) {
const fileSink = new PinoFileSink(this.fileSinkOpts);
this.activeFileSink = fileSink;
- return pino(this.options, pino.multistream([{ stream: prettyStream }, { stream: fileSink }]));
+ return pino(
+ { ...this.options, level: instanceLevel },
+ pino.multistream([
+ { stream: prettyStream, level: consoleLevel },
+ { stream: fileSink, level: fileLevel },
+ ]),
+ );
}
- return pino(this.options, prettyStream);
+ return pino({ ...this.options, level: consoleLevel }, prettyStream);
}
private recreateInstance(): void {
@@ -129,6 +162,26 @@ export class PinoLogger {
this.recreateInstance();
}
+ reconfigure(config: PinoLoggerConfig): void {
+ if (config.options) {
+ this.options = { ...this.options, ...config.options };
+ }
+ if (config.transportConfigs) {
+ this.transportConfigs = config.transportConfigs;
+ }
+ if (config.fileSink) {
+ this.fileSinkOpts = config.fileSink;
+ }
+ if (config.redactPaths && config.redactPaths.length > 0) {
+ this.redactPaths = config.redactPaths;
+ this.options = {
+ ...this.options,
+ redact: { paths: [...config.redactPaths], censor: '[REDACTED]' },
+ };
+ }
+ this.recreateInstance();
+ }
+
getPinoInstance(): PinoLoggerInstance {
return this.pinoInstance;
}
@@ -168,6 +221,12 @@ class LoggerFactory {
configure(config: LoggerFactoryConfig): void {
this.config = config;
+ if (config.pinoConfig && !config.defaultLogger && !config.loggerFactory) {
+ for (const logger of this.loggers.values()) {
+ logger.reconfigure(config.pinoConfig);
+ }
+ return;
+ }
this.loggers.clear();
}