NestJS Logging into File, Database, etc using either default logger or npm like winston

user3497702 picture user3497702 · Sep 26, 2019 · Viewed 7.9k times · Source

NestJS implemented with default logger. It send the output to console.

May I know, How to configure the default logger to send the output to file, database.

In addition,

if I want to use Winston in NestJS, how to use/inject/extend with various transport option.

It should not be tighly coupled with NestJS and always able to replace with some other logger.

Answer

Frébo picture Frébo · Oct 16, 2019

You cannot configure the default logger to send the output somewhere else.
You need to create a custom logger or better: Extend the default logger to implement your needs.

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

export class MyLogger extends Logger {
  error(message: string, trace: string) {
    // write the message to a file, send it to the database or do anything
    super.error(message, trace);
  }
}

Read the documentation to see how to implement this.

But if you want to use Winston anyway there is no need to reinvent the wheel, you can use the the awesome npm package nest-winston.

First you need to register the WinstonModule in your app.module.ts

import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
[...]

@Module({
  imports: [
    TypeOrmModule.forRoot(typeOrmConfig),
    WinstonModule.forRoot({
      transports: [
        new winston.transports.Console(),
      ],
    }),
    SearchesModule,
    SuggestionsModule,
  ],
})
export class AppModule {}

Then you can inject and use the logger anywhere like this:

import { Injectable, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Logger } from 'winston';
import { SuggestionsRepository } from './suggestions.repository';

@Injectable()
export class SuggestionsService {

  constructor(
    @InjectRepository(SuggestionsRepository)
    private repository: SuggestionsRepository,
    @Inject('winston')
    private readonly logger: Logger,
  ) { }

  getAllSuggestions = async () => {
    this.logger.info('Returning suggestions...');
    return await this.repository.getAll();
  }
}

Read the documentation for more examples.