I'm currently trying to extend my logging class in my NestJS (v7) application with a unique request id. When I try to insert my request scoped service in my transient logger, the logger is always undefined
if I inject it somewhere.
winston-logger.class.ts
import { Injectable, Scope } from '@nestjs/common';
import { Logger } from 'winston';
import { RequestInjector } from './request-injector.class';
import { WinstonAdapter } from './winston.adapter';
@Injectable({ scope: Scope.TRANSIENT })
export class WinstonLogger {
private readonly logger: Logger;
private requestId = 'default';
private context = 'default';
constructor(private readonly winstonAdapter: WinstonAdapter, private readonly requestInjector: RequestInjector) {
this.logger = this.winstonAdapter.getLogger();
this.requestId = this.requestInjector.getRequestId();
}
log(level: string, message: string, ...meta: any[]): void {
meta.push({ requestId: this.requestId });
this.logger.log(level, message, ...meta);
}
setContext(context: string) {
this.context = context;
}
}
request-injector.class.ts
import { Injectable, Scope } from '@nestjs/common';
@Injectable({ scope: Scope.REQUEST })
export class RequestInjector {
private requestId = 'default';
constructor() {}
setRequestId(requestId: string) {
this.requestId = requestId;
}
getRequestId(){
return this.requestId;
}
}
If I change the RequestInjector
to DEFAULT
(Singleton) or to TRANSIENT
the logger is defined but if I change it to REQUEST
the logger is undefined
if I inject it somewhere. Am I missing something, why this doesn't work?
I can't change the scope of my logger because the context in my logger is TRANSIENT
.
What I'm trying to achieve is that every class that injects my logger has its own context but should have the same requestId for a request.
question from:
https://stackoverflow.com/questions/65841451/nestjs-request-scoped-service-in-transient-logger 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…