Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 441
user3497702 Avatar asked Sep 26 '19 17:09

user3497702


People also ask

What logger does Nestjs use?

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). This functionality is provided via the Logger class in the @nestjs/common package.

What is Winston logger in node JS?

Winston is the most popular logging library for Node. js. It aims to make logging more flexible and extensible by decoupling different aspects such as log levels, formatting, and storage so that each API is independent and many combinations are supported. It also uses Node.


2 Answers

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.

like image 87
Frébo Avatar answered Sep 18 '22 14:09

Frébo


Here is how to implement logging result at files

 WinstonModule.forRoot({
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json(),
      ),
      transports: [
        new winston.transports.Console(),
        new winston.transports.File({
          dirname: path.join(__dirname, './../log/debug/'), //path to where save loggin result 
          filename: 'debug.log', //name of file where will be saved logging result
          level: 'debug',
        }),
        new winston.transports.File({
          dirname: path.join(__dirname, './../log/info/'),
          filename: 'info.log',
          level: 'info',
        }),
      ],
    }),
like image 26
Vakho Jgenti Avatar answered Sep 16 '22 14:09

Vakho Jgenti