How to Use Nestjs Logging Service

NestJS How to add custom Logger to custom ExceptionFilter

First of all your class ForbiddenException extends HttpException is not
what it calls ExceptionFilter. ExceptionFilter is

exceptions layer which is responsible for processing all unhandled exceptions across an application

docs

You provided exmaple when you are trying to inject it to your custom HttpException. But thats wrong. Your exception don't have to be responsible for logging. Thats what ExceptionFilter should be responsible for.

Anyway, for now (17 oct 2019) there is no example in official docs how to inject providers to ExceptionFilter.

You can pass it to constructor on init, but you should to get Logger instance before with app.get<T>(...) method.

For example I've changed code from exception-filters docs:

// HttpExceptionFilter.ts

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
import {MyLogger} from '../MyLogger'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
constructor(private readonly logger: MyLogger) {}

catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();

if (status >= 500) {
this.logger.error({ request, response });
}

response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}

and bootstrap.ts code:

// bootstrap.ts

const app = await NestFactory.create(MainModule, {
logger: false,
});

const logger = app.get<MyLogger>(MyLogger);
app.useLogger(logger);
app.useGlobalFilters(new HttpExceptionFilter(logger));

This technique can be used for all this INestApplication methods:

  • app.useGlobalFilters
  • app.useGlobalGuards
  • app.useGlobalInterceptors
  • app.useGlobalPipes
  • app.useLogger
  • app.useWebSocketAdapter

NestJS: How to customise log messages to include request id and name of the file the log message occurred

I managed to get it working using the nest-pino library:

// main.ts

import { Logger } from 'nestjs-pino';

async function bootstrap() {

const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
{ bufferLogs: true }
);

app.useLogger(app.get(Logger));

}
bootstrap();

Logging request/response in Nest.js

I ended up injecting a classic logger on the raw app.
This solution is not the best since it is not integrated to the Nest flow but works well for standard logging needs.

import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { ApplicationModule } from './app.module';
import * as morgan from 'morgan';

async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(ApplicationModule, new FastifyAdapter());
app.use(morgan('tiny'));

await app.listen(process.env.PORT, '0.0.0.0');
}

if (isNaN(parseInt(process.env.PORT))) {
console.error('No port provided. ');
process.exit(666);
}

bootstrap().then(() => console.log('Service listening : ', process.env.PORT));

NestJS - avoid setContext() in constructor on logger injection

When you do private logger: LoggerService, there's no chance to make that .setContext(Service.name) call.

What you could do is something like:

@Logger(Service.name) private logger: LoggerService

How? Read this article: Advanced NestJS: Dynamic Providers



Related Topics



Leave a reply



Submit