Skip to content

Commit

Permalink
[feat] Automatically provide context based on INQUIRER
Browse files Browse the repository at this point in the history
Resolves #532
  • Loading branch information
Ginden committed Oct 12, 2021
1 parent e20a777 commit 184bfde
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion __tests__/no-context.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('no context', () => {

const ctrlLog = logs.find((v) => v.msg === msg);
expect(ctrlLog).toBeTruthy();
expect(ctrlLog).not.toHaveProperty('context');
expect(ctrlLog?.context).toEqual(TestController.name);
});
});
}
Expand Down
1 change: 1 addition & 0 deletions __tests__/utils/test-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
19 changes: 18 additions & 1 deletion src/InjectPinoLogger.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
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<string>();
const transientToken = getLoggerToken('');

export function InjectPinoLogger(context = '') {
decoratedLoggers.add(context);
return Inject(getLoggerToken(context));
}

function createDecoratedLoggerProvider(context: string): Provider<PinoLogger> {
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) => {
Expand Down

0 comments on commit 184bfde

Please sign in to comment.