Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS: How to set global log level for different environments

Tags:

logging

nestjs

I am using the NestJS in-built logger. I couldn't find an option to set the global log level. For e.g. log level as 'verbose' for dev environment and log level as 'error' for prod environment.

Also, is there an option to disable the stuff that NestJS adds in the output i.e timestamp and other info and only log the message? I need this as we use Kibana logs and it automatically adds the required fields.

like image 827
Ramandeep Singh Avatar asked Aug 04 '19 08:08

Ramandeep Singh


People also ask

What logger does Nestjs use?

Nest comes with a built-in text-based logger which is used during application bootstrapping and several other circumstances such as displaying caught exceptions (i.e., system logging). This functionality is provided via the Logger class in the @nestjs/common package.

How do you change the log level?

To change log levels as a root user, perform the following: To enable debug logging, run the following command: /subsystem=logging/root-logger=ROOT:change-root-log-level(level=DEBUG) To disable debug logging, run the following command: /subsystem=logging/root-logger=ROOT:change-root-log-level(level=INFO)


Video Answer


2 Answers

You can set up log levels in your main.ts file:

const app = await NestFactory.create(AppModule, {
  logger: process.env.NODE_ENV === 'development' ? ['log', 'debug', 'error', 'verbose', 'warn'] : ['error', 'warn'],
});
like image 150
icl7126 Avatar answered Oct 22 '22 06:10

icl7126


You can write your own Logger with that logic and use it as a service or you can set it globally

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

const app = await NestFactory.create(ApplicationModule, {
  logger: new MyLogger(),
});
like image 20
Maciej Sikorski Avatar answered Oct 22 '22 08:10

Maciej Sikorski