npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@aguirresabino/nestjs-logger

v4.1.0

Published

Logger for NestJS

Downloads

19

Readme

NestJS Logger

NestJS Logger is a powerful logging library for NestJS applications, built on top of Pino.

Features

  • Customizable logging levels
  • Asynchronous local storage for correlation IDs
  • Integration with NestJS
  • Support for multiple logger contexts

Installation

To install the library, use the following command:

npm install @aguirresabino/nestjs-logger

or with Yarn:

yarn add @aguirresabino/nestjs-logger

Usage

Basic Usage

To use the logger in your NestJS application, you can import and configure the LoggerModule using either forRoot, forRootAsync with useFactory, or forRootAsync with useClass:

Using forRoot

import { Module } from '@nestjs/common';
import { LoggerModule } from '@aguirresabino/nestjs-logger';

@Module({
  imports: [
    LoggerModule.forRoot({
      pino: {
        enabled: true,
        level: 'info',
      }
    }),
  ],
})
export class AppModule {}

Using forRootAsync with useFactory

import { Module } from '@nestjs/common';
import { LoggerModule } from '@aguirresabino/nestjs-logger';

@Module({
  imports: [
    LoggerModule.forRootAsync({
      useFactory: () => ({
        pino: {
          enabled: true,
          level: 'info',
        }
      }),
    }),
  ],
})
export class AppModule {}

Using forRootAsync with useClass

import { Module } from '@nestjs/common';
import { LoggerModule, LoggerModuleOptionsFactory, LoggerModuleOptions } from '@aguirresabino/nestjs-logger';

class LoggerConfigService implements LoggerModuleOptionsFactory {
  createLoggerOptions(): LoggerModuleOptions {
    return {
      pino: {
        enabled: true,
        level: 'info',
      }
    };
  }
}

@Module({
  imports: [
    LoggerModule.forRootAsync({
      useClass: LoggerConfigService,
    }),
  ],
})
export class AppModule {}

The AppLogger class can be used to replace the default NestJS logger. It implements the LoggerService interface. To replace the default logger, you can do this:

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import {
  AppLoggerFactory,
  DEFAULT_APP_LOGGER
} from '@aguirresabino/nestjs-logger';
import { AppModule } from './app.module';

async function bootstrap() {
  const app: NestExpressApplication = await NestFactory.create<NestExpressApplication>(AppModule, {
    abortOnError: false,
    logger: AppLoggerFactory.get(),
  });
  app.useLogger(app.get(DEFAULT_APP_LOGGER));
}
void bootstrap();

Now, you can inject a logger into a service or other injectable class using the @InjectLogger decorator:

import { Injectable } from '@nestjs/common';
import { InjectLogger, Logger } from '@aguirresabino/nestjs-logger';

@Injectable()
export class MyService {
  constructor(
    @InjectLogger(MyService.name) private readonly logger: Logger,
  ){}
}

Using the Logger Outside of NestJS

The AppLogger class can also be used outside of the NestJS dependency injection context. This can be useful for logging in other parts of your code that do not use NestJS:

import { AppLoggerFactory } from '@aguirresabino/nestjs-logger';

const logger = AppLoggerFactory.get();

logger.log('This is a log message');
logger.log('This is a log message with context', 'Context');

Correlation Key

The library automatically manages a correlationKey for tracking log entries across requests:

  • In HTTP requests, the correlation key is extracted from the x-request-id header in the HttpLoggerMiddleware. If the header is missing, the middleware assigns a new unique value.

  • In addition, the LoggerLocalAsyncStorageInterceptor checks the current asynchronous storage context. If no correlationKey is present, it generates one. This ensures that a correlation identifier is always available for logs.

By default, the library generates the correlationKey if none is provided. However, if you wish to supply your own, simply include the correlationKey property in your log data. For example:

this.logger.info({ foo: 'bar', correlationKey: '1234' }, 'Hello, World!');

For a complete example using these features, see our pino-http-microservice.ts example.

Hybrid Applications (HTTP and Microservice)

Hybrid applications allow you to combine an HTTP-based NestJS application with microservices in a single application. In such scenarios, it is crucial to enable the inheritAppConfig option during the microservice connection. This option ensures that global configuration (such as pipes, interceptors, guards, and filters) from the main HTTP application is shared with the microservice context.

This is especially important when using global interceptors like the LoggerLocalAsyncStorageInterceptor. This interceptor utilizes Node.js's AsyncLocalStorage to create a local context (for example, assigning a unique correlation key to each request) that is essential for tracking and logging request-specific data.

For example:

import { Transport, MicroserviceOptions } from '@nestjs/microservices';

const microservice = app.connectMicroservice<MicroserviceOptions>(
  {
    transport: Transport.TCP,
  },
  { inheritAppConfig: true },
);

For a complete hybrid application example using this approach, see our pino-http-microservice.ts example.

Contributing

Contributions are welcome! Please read our Contributing Guide to learn how you can help.

License

This project is licensed under the MIT License. See the LICENSE file for more details.

Changelog

See the CHANGELOG for a history of changes to this project.

Acknowledgements

This project was inspired by the nestjs-pino package.