Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

NestJS - Request scoped service in transient logger

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...