Skip to content

Commit

Permalink
[feat] Automatically provide context based on INQUIRER
Browse files Browse the repository at this point in the history
Resolves iamolegga#532
  • Loading branch information
Ginden committed Sep 2, 2021
1 parent cb3b778 commit 5d54339
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
3 changes: 2 additions & 1 deletion __tests__/no-context.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
}
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 5d54339

Please sign in to comment.