Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable colored console output

Tags:

logging

nestjs

Is it possible to disable the colored console output of the NestJS default logger? I can't find an option to turn it off :-(

(Some more text, because this question is too simple for StackOverflow.)

like image 787
Andreas N. Avatar asked Apr 01 '20 09:04

Andreas N.


3 Answers

The logger service uses module cli-color, setting environment variable NO_COLOR disables the output of color codes.

like image 166
Andreas N. Avatar answered Oct 08 '22 20:10

Andreas N.


While @Andreas's 2nd part of the answer is correct about setting the environment variable NO_COLOR, the first part is wrong. NestJS (at least as of v8) does not use the cli-color module (maybe earlier they were using it).

Seems they have implemented their own clc thing but they do respect the NO_COLOR flag.

Source code- https://github.com/nestjs/nest/blob/v8.0.8/packages/common/utils/cli-colors.util.ts#L3

And their documentation also says the same thing-

HINT
To disable color in the default logger's messages, set the NO_COLOR environment variable.

So below is the output in my local when running without the variable-

enter image description here

And this is when I do export NO_COLOR=true-

enter image description here

This works well in AWS CloudWatch logs as well.

like image 38
Shashank Agrawal Avatar answered Oct 08 '22 19:10

Shashank Agrawal


you can implementing your own custom logger. Simply implement each of the methods of the LoggerService interface as shown below. import { LoggerService } from '@nestjs/common';

export class MyLogger implements LoggerService {
  log(message: string) {
    /* your implementation */
  }
  error(message: string, trace: string) {
    /* your implementation */
  }
  warn(message: string) {
    /* your implementation */
  }
  debug(message: string) {
    /* your implementation */
  }
  verbose(message: string) {
    /* your implementation */
  }
}

const app = await NestFactory.create(ApplicationModule, {
  logger: new MyLogger(),
});
await app.listen(3000);

Rather than writing a logger from scratch, you may be able to meet your needs by extending the built-in Logger class and overriding selected behavior of the default implementation.

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

export class MyLogger extends Logger {
  error(message: string, trace: string) {
    // add your tailored logic here
    super.error(message, trace);
  }
}

https://docs.nestjs.com/techniques/logger

like image 3
har17bar Avatar answered Oct 08 '22 21:10

har17bar