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 d29065a
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ export class MyService {
private readonly logger: PinoLogger
) {}

constructor(
// If InjectPinoLogger is used without argument, it will attempt to deduce context
// using INQUIRER injection https://github.com/nestjs/docs.nestjs.com/issues/937
@InjectPinoLogger()
private readonly logger: PinoLogger
) {}

foo() {
// PinoLogger has same methods as pino instance
this.logger.trace({ foo: 'bar' }, 'baz %s', 'qux');
Expand Down
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
22 changes: 21 additions & 1 deletion src/InjectPinoLogger.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,36 @@
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 (!inquirer) {
return logger;
}
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 d29065a

Please sign in to comment.