Lesson 21 / 34

Logging

Log at the right levels with Nest's built-in Logger and plug in Winston or Pino for production logging.

Built-in Logger

Inject Logger to log at different levels: debug, log, warn, error.

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

@Injectable()
export class UsersService {
  private readonly logger = new Logger(UsersService.name);

  create(user: User) {
    this.logger.log(`Creating user: ${user.email}`);
    return this.userRepository.save(user);
  }
}

Third-party loggers

Winston, Pino, or Bunyan—configure them in your main.ts or as a custom provider.

Quick check

Quick check: Why create `new Logger(UsersService.name)`?

  • It adds the class name as the log context
  • It disables console output
  • It writes logs to a file
Answer

It adds the class name as the log context — The context label shows which class emitted each line.