user3497702
user3497702

Reputation: 851

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.

Upvotes: 22

Views: 45650

Answers (3)

Vakho Jgenti
Vakho Jgenti

Reputation: 405

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',
        }),
      ],
    }),

Upvotes: 6

Zakaria Eddiba
Zakaria Eddiba

Reputation: 19

In Linux you can simply pipe the stdout to a file: npm run start > app.log

in Powershell you can use Out-File probably like this (not a powershell expert though) npm run start | Out-File -filepath app.log

So logger libs also support direct file output handling within your app code.

Upvotes: 1

Frébo
Frébo

Reputation: 678

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.

Upvotes: 36

Related Questions