Logger Methods

  • 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)

  • You can fully control the behavior of the logging system, including any of the following:

    • disable logging entirely
    • specify the log level of detail (e.g., display errors, warnings, debug information, etc.)
    • override timestamp in the default logger (e.g., use ISO8601 standard as date format)
    • completely override the default logger
    • customize the default logger by extending it
    • make use of dependency injection to simplify composing and testing your application
    import { Logger } from "@nestjs/common";

export class BookService {

private readonly logger = new Logger(BookService.name);

addBook(name: string) {
try{
this.logger.log('adding book to db...');
this.logger.debug("Book name:{}", name)
}catch(err){
logger.error("error", err);
logger.error("Unable to add book :{}", err.message);
}
}

}
  • Logs
[Nest] 19096   - 01/02/2024, 7:12:59 AM   [NestFactory] Starting Nest application...

Disable Logging

  • main.ts
    const app = await NestFactory.create(AppModule, {
logger: false,
});
await app.listen(3000);

Enable Logging

    const app = await NestFactory.create(AppModule, {
logger: ['error', 'warn'],
});
await app.listen(3000);
  • Values in the array can be any combination of 'log', 'fatal', 'error', 'warn', 'debug', and 'verbose'.