perf(logger): stop building a throwaway pino root per child (#2132)

This commit is contained in:
Hampus authored and GitHub committed 2026-08-30 22:15:40 +02:00
1 parent e14d193b43
commit 723f0d6e6e
6 files changed
+105 -19

No files matched your search

+8 -5
View File
@@ -111,8 +111,13 @@ function createPinoLogger(serviceName: string, options: LoggerOptions = {}): Pin
export class Logger {
private logger: PinoLogger;
constructor(serviceName: string, options: LoggerOptions = {}) {
this.logger = createPinoLogger(serviceName, options);
constructor(serviceName: string, options?: LoggerOptions);
constructor(pinoLogger: PinoLogger);
constructor(serviceNameOrPinoLogger: string | PinoLogger, options: LoggerOptions = {}) {
this.logger =
typeof serviceNameOrPinoLogger === 'string'
? createPinoLogger(serviceNameOrPinoLogger, options)
: serviceNameOrPinoLogger;
}
getPinoLogger(): PinoLogger {
@@ -124,9 +129,7 @@ export class Logger {
}
static createWithLogger(logger: PinoLogger): Logger {
const childLogger = new Logger('', {});
childLogger.setPinoLogger(logger);
return childLogger;
return new Logger(logger);
}
trace(obj: Record<string, unknown>, msg?: string): void;
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createLogger, Logger} from '@fluxer/logger/src/Logger';
import pino, {type Logger as PinoLogger} from 'pino';
import {afterEach, describe, expect, it, vi} from 'vitest';
function readDestination(logger: PinoLogger): unknown {
return (logger as unknown as Record<symbol, unknown>)[pino.symbols.streamSym];
}
describe('Logger.child', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
it('shares the parent destination instead of opening a new one', () => {
const parent = createLogger('logger-test', {environment: 'production'});
const child = parent.child({logger: 'ChildService'});
expect(child).toBeInstanceOf(Logger);
expect(readDestination(child.pino)).toBe(readDestination(parent.pino));
});
it('does not construct a throwaway pino root logger', () => {
vi.stubEnv('FLUXER_ENV', 'production');
const parent = createLogger('logger-test', {environment: 'production'});
const destinationSpy = vi.spyOn(pino, 'destination');
const child = parent.child({logger: 'ChildService'});
expect(destinationSpy).not.toHaveBeenCalled();
expect(child.pino.bindings()['logger']).toBe('ChildService');
});
it('keeps the parent bindings on the child', () => {
const parent = createLogger('logger-test', {environment: 'production'});
const child = parent.child({logger: 'ChildService'});
expect(child.pino.bindings()['service']).toBe('logger-test');
expect(child.pino.level).toBe(parent.pino.level);
});
});