0

I am working on an application where I have to use Winston for logging purposes in Nest.js. I want to implement a scenario where I want to specify the transport on which I want to log the message.

For example, I have two transporters like console and file. I want some log messages to be logged in the file. While others to be consoled but not both at the same time.

There is a way to use multiple loggers in Winston but unfortunately, the wrapper package nest-winston doesn't have this functionality. So, I tried a custom logger as:


import { Injectable, LoggerService } from '@nestjs/common';
import winston, { transports } from 'winston';
import { WinstonModule } from 'nest-winston';

@Injectable()
export class CustomLogger implements LoggerService {
  logger = WinstonModule.createLogger({
      transports: [
        new winston.transports.File({ filename: 'combined.log' })
      ]
  });
  consoleLogger = WinstonModule.createLogger({
    transports: [
      new winston.transports.Console(),
    ]
  });

  log(message: string, options: any) {    
    if(options.logger === "logger"){
      this.logger.log({ level: options.level, message });
    }else{
      this.consoleLogger.log({ level: options.level, message });
    }
  }

  error(message: string, trace: string, options: any) {
    if(options.logger === "logger"){
      this.logger.error({ level: options.level, message });
    }else{
      this.consoleLogger.error({ level: options.level, message });
    }
  }
}

I have imported the logger module in the module I want to use and then I am calling it like:

@Injectable()
export class TestingService {
  constructor(
    private logger: CustomLogger
  ) { }

  async createLog(message: string, level: string): Promise<void> {
   this.logger.log(message, { logger: "logger", level });
  }
}

It is configured correctly. No build errors are there but it is not logging as expected. Can you suggest a solution to this problem? Thanks.

Muhammad Zeeshan
  • 4,608
  • 4
  • 15
  • 41
  • To answer this, you'll need to provide a bit more info on what it's currently logging, how you're calling it, and how you're injecting it. I don't see anything obvious that's wrong with this setup. – HMilbradt Oct 06 '21 at 00:22
  • From the update I don't see anything that looks incorrect. What exactly is being logged that's unexpected? The only thing that I can see that might cause issues is using the nest winston module. Is there a reason you can't just use winston directly? – HMilbradt Oct 06 '21 at 14:54

0 Answers0