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.