how to customize nest.js logger

Viewed 719

I want to remove the default log format, and use only custom log message. ::1 2021-08-10T10:29:52.000Z PUT / http 200 18 3000 27ms I need help creating custom logger and below is the codes I have so far. it logs with default log format [Nest] 28869 - 2021. 08. 10 10:23:03AM LOG ${custom log message}

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next) {
    const now = Date.now();
    const req = context.switchToHttp().getRequest();
    const method = req.method;
    const url = req.url;

    return next.handle().pipe(
      tap(() => {
        const res = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        Logger.log(
          `${req.ip} ${new Date()} ${method} ${url} ${req.protocol} ${res.statusCode} ${
            req.headers['content-length'] || '0'
          } ${req.headers.host.split(':')[1]} ${delay}ms`,
        );
      }),
    );
  }
}

Thank you in advance!

1 Answers

You can do this by overwriting the default logger and using that logger when the app bootstrap in main.ts.

Your custom logger is something like this.

import { LoggerService } from '@nestjs/common';

export class CustomLogger implements LoggerService {
  /**
   * Write a 'log' level log.
   */
  log(message: any, ...optionalParams: any[]) {
     console.log(message);
  }

  /**
   * Write an 'error' level log.
   */
  error(message: any, ...optionalParams: any[]) {}

  /**
   * Write a 'warn' level log.
   */
  warn(message: any, ...optionalParams: any[]) {}

  /**
   * Write a 'debug' level log.
   */
  debug?(message: any, ...optionalParams: any[]) {}

  /**
   * Write a 'verbose' level log.
   */
  verbose?(message: any, ...optionalParams: any[]) {}
}

Then create a module and provide the customer logger to that module. And make it global so you can use it anywhere on your code.

import { Module, Global } from '@nestjs/common';
import { CustomLogger } from './logger.service';
import { LoggingInterceptor } from './logging.interceptor';

@Global()
@Module({
  providers: [CustomLogger, LoggingInterceptor],
  exports: [CustomLogger],
})
export class LoggerModule {
}

Register LoggerMoudle in your AppModule. Add customer logger to your main.ts.


import { CustomLogger } from './logger/logger.service';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });
  app.useLogger(app.get(CustomLogger));
  await app.listen(PORT)
}

Then you can inject the customeLogger service into the Logging interceptor and your work is done.

import { CustomLogger } from './logger.service';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  constructor(private customLogger: CustomLogger) {}
  intercept(context: ExecutionContext, next) {
    const now = Date.now();
    const req = context.switchToHttp().getRequest();
    const method = req.method;
    const url = req.url;

    return next.handle().pipe(
      tap(() => {
        const res = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        this.customLogger.log(
          `${req.ip} ${new Date()} ${method} ${url} ${req.protocol} ${res.statusCode} ${
            req.headers['content-length'] || '0'
          } ${req.headers.host.split(':')[1]} ${delay}ms`,
        );
      }),
    );
  }
}
Related