close
close

Understanding the NestJS Logger: Format Specifiers and Logging Best Practices

Understanding the NestJS Logger: Format Specifiers and Logging Best Practices

NestJS is a powerful framework for building scalable server-side applications, and its built-in logging module is an essential tool for monitoring and debugging. While working with the @nestjs/common logger, you might wonder about its capabilities, especially whether it supports format specifiers such as %s And %d in the same way console.log do.

In this blog post, we will explore the @nestjs/common logger, its support for format specifiers, and some best practices for efficient logging in your NestJS applications.

NestJS Logger Basics

NestJS provides a built-in logging module which includes various methods such as log, error, warn, debugAnd verbose. These methods allow developers to log messages at different severity levels. Here is a simple example of using the NestJS logger:

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

class AppService {
  private readonly logger = new Logger(AppService.name);

  getHello(): string {
    this.logger.log('Hello World!');
    return 'Hello World!';
  }
}
Enter full screen mode

Exit full screen mode

Support for format specifiers

Through practical tests it has been confirmed that @nestjs/common logger supports format specifiers such as %s, %dand more. This feature can be extremely useful for creating formatted log messages. Here are some examples:

this.logger.warn('%s is deprecated', 'activity'); // Logs: activity is deprecated
this.logger.error('%d errors occurred', 5); // Logs: 5 errors occurred
Enter full screen mode

Exit full screen mode

Limits and good practices

While the NestJS logger supports format specifiers, it does not support logging a string followed by an object as parameters directly. Here are some examples to illustrate what is and is not supported:

Supported:

this.logger.error('%s', 'test'); // Logs: test
this.logger.error({ test: 'test' }); // Logs: { test: 'test' }
this.logger.error(`test: ${{ test: 'test' }}`); // Logs: test: (object Object)
Enter full screen mode

Exit full screen mode

Unsupported:

this.logger.error('test', { test: 'tester' }); // This will not log the object properly
Enter full screen mode

Exit full screen mode

Recommendations for effective journaling

  1. Use literal templates for complex logs:When you need to include variables or objects in your logs, use template literals for clarity and readability.

    const user = { id: 1, name: 'John' };
    this.logger.log(`User logged in: ${JSON.stringify(user)}`);
    
  2. Logging Levels:Use appropriate logging levels (log, warn, error, debug, verbose) to sort your logs according to their importance.

  3. Structured Logging: For more complex logging needs, consider using structured logging with JSON. This can be especially useful for logging services like Elasticsearch, Logstash, and Kibana (ELK stack).

  4. External Libraries:For advanced logging features, consider integrating with libraries such as nestjs-pino which supports JSON logging and has better performance characteristics.

    import { LoggerModule } from 'nestjs-pino';
    
    @Module({
      imports: (
        LoggerModule.forRoot(),
      ),
      controllers: (AppController),
      providers: (AppService),
    })
    export class AppModule {}
    

Conclusion

THE @nestjs/common logger is a robust tool that supports format specifiers, making it easy to format your log messages. However, it has some limitations when it comes to directly logging objects with string messages. By understanding these capabilities and adopting best practices, you can improve your logging strategy and make your NestJS applications easier to maintain and debug.


The references