diff --git a/__tests__/no-context.spec.ts b/__tests__/no-context.spec.ts index fae022259..fdc324514 100644 --- a/__tests__/no-context.spec.ts +++ b/__tests__/no-context.spec.ts @@ -54,8 +54,9 @@ describe('no context', () => { .run(); const ctrlLog = logs.find((v) => v.msg === msg); + console.log(ctrlLog); expect(ctrlLog).toBeTruthy(); - expect(ctrlLog).not.toHaveProperty('context'); + expect(ctrlLog?.context).toEqual(TestController.name); }); }); } diff --git a/__tests__/utils/test-case.ts b/__tests__/utils/test-case.ts index f3ebf538b..6d8e19388 100644 --- a/__tests__/utils/test-case.ts +++ b/__tests__/utils/test-case.ts @@ -83,6 +83,7 @@ export class TestCase { __resetSingletons(); const app = await NestFactory.create(this.module, this.adapter, { + abortOnError: false, bufferLogs: true, }); app.useLogger(app.get(Logger)); diff --git a/src/InjectPinoLogger.ts b/src/InjectPinoLogger.ts index 94bd77670..ca3a87de6 100644 --- a/src/InjectPinoLogger.ts +++ b/src/InjectPinoLogger.ts @@ -1,9 +1,11 @@ -import { Inject, Provider } from '@nestjs/common'; +import { Inject, Provider, Scope } from '@nestjs/common'; +import { INQUIRER } from '@nestjs/core'; import { PinoLogger } from './PinoLogger'; const decoratedTokenPrefix = 'PinoLogger:'; const decoratedLoggers = new Set(); +const transientToken = getLoggerToken(''); export function InjectPinoLogger(context = '') { decoratedLoggers.add(context); @@ -11,6 +13,21 @@ export function InjectPinoLogger(context = '') { } function createDecoratedLoggerProvider(context: string): Provider { + if (context === '') { + return { + provide: transientToken, + useFactory: (logger: PinoLogger, inquirer: any) => { + if (typeof inquirer === 'string') { + logger.setContext(inquirer); + } else if (typeof inquirer === 'object') { + logger.setContext(inquirer.constructor.name); + } + return logger; + }, + inject: [PinoLogger, INQUIRER], + scope: Scope.TRANSIENT, + }; + } return { provide: getLoggerToken(context), useFactory: (logger: PinoLogger) => {