Kam
Kam

Reputation: 6008

How can I make the HTTP request object visible to my winston logger?

I'm building a NestJS based application and using nest-winston for logging.

I would like to log the incoming request header with every log message. For that I need to somehow extract the HTTP context from nestjs and pass it to nest-winston.

I'm unable to find how to do either. If this is not doable in nest-winston I don't mind using winston directly.

Upvotes: 1

Views: 2319

Answers (2)

Adrian H
Adrian H

Reputation: 317

I think you can use middleware to solve this specific problem. Check https://docs.nestjs.com/middleware

The middleware could look like this (did not test it):

import { NextFunction, Request, Response } from 'express';
import {Inject, Injectable,NestMiddleware} from '@nestjs/common';
import * as http from 'http';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
    constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) {
    }

    public use(request: Request, response: Response, next: NextFunction): void {
        const {body, method, originalUrl, headers} = request;
        this.logger.log({body, method, originalUrl, headers})

    }
}

And you could apply it like this:

export class AppModule implements NestModule {
    public configure(consumer: MiddlewareConsumer): void {
        consumer
            .apply(LoggerMiddleware)
            .forRoutes('*');
    }
}

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70131

To my knowledge it isn't doable with the nest-winston module because its logger is not REQUEST scoped. You'll need to create your own dynamic module and have your service as REQUEST scoped. Then you can use @Inject(REQUEST) to have the request added to each instance of the winston service you'd create.

With that said, there are some drawbacks to request scoped classes, namely resource consumption as not only will the service have to be re-instantiated, but every service that depends on that winston service, and then every service up the line until you reach the controller. Just something to keep in mind

Upvotes: 2

Related Questions