Custom Log
src/middleware/logger/logger.service.ts
import { ConsoleLogger, Injectable } from "@nestjs/common";
@Injectable()
export class LoggerService extends ConsoleLogger {
constructor() {
super()
this.setLogLevels(['verbose', 'debug', 'log', 'warn', 'error'])
}
appLog(message: string) {
this.log(message)
}
errorLog(message: string) {
this.error(message);
}
}
src/middleware/logger/logger.module.ts
import { Module } from "@nestjs/common";
import { LoggerService } from "./logger.service";
@Module({
providers: [LoggerService],
exports: [LoggerService]
})
export class LoggerModule {}
src/api/api.module.ts → imports: [LoggerModule]
import { Module } from '@nestjs/common';
import { ApiController } from './api.controller';
import { ApiService } from './api.service';
import { LoggerModule } from '@src/middleware/logger/logger.module';
@Module({
imports: [LoggerModule],
controllers: [ApiController],
providers: [ApiService]
})
export class ApiModule {}
src/api/api.controller.ts
import { Controller, Get } from '@nestjs/common';
import { LoggerService } from '@src/middleware/logger/logger.service';
@Controller('api')
export class ApiController {
constructor(private loggerService: LoggerService) {
loggerService.setContext(ApiController.name)
}
@Get('app')
app() {
this.loggerService.appLog('application log')
}
@Get('error')
error() {
this.loggerService.errorLog('error log')
}
}
변수로 선언해서 사용
main.ts
const logger = new LoggerService();
logger.setContext('main.ts')
async function bootstrap() {
...
logger.appLog(`load main.ts`)
...
}
bootstrap();
Middleware Log
미들웨어를 통해 API Request 요청 로그를 남겨보자
src/middleware/logger/logger.express.ts
import { Injectable, NestMiddleware } from "@nestjs/common";
import { LoggerService } from "./logger.service";
import { NextFunction } from "express";
@Injectable()
export class LoggerExpress implements NestMiddleware {
constructor(private loggerService: LoggerService) {
this.loggerService.setContext(LoggerExpress.name)
}
use(req: Request, res: Response, next: NextFunction) {
this.loggerService.verbose(`${req.url} [${req.method}] ${JSON.stringify(req.body)}`);
next();
}
}
src/middleware/logger/logger.fastify.ts
import { Injectable, NestMiddleware } from "@nestjs/common";
import { LoggerService } from "./logger.service";
import { FastifyReply, FastifyRequest } from "fastify";
// $ npm i fastify
@Injectable()
export class LoggerFastify implements NestMiddleware {
constructor(private loggerService: LoggerService) {
this.loggerService.setContext(LoggerFastify.name)
}
use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void) {
this.loggerService.warn(`${req.url} [${req.method}]`);
next()
}
}
src/app.module.ts
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ApiModule } from './api/api.module';
import { LoggerFastify } from './middleware/logger/logger.fastify';
import { LoggerModule } from './middleware/logger/logger.module';
import { LoggerExpress } from './middleware/logger/logger.express';
@Module({
imports: [ApiModule, LoggerModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
/*
path: '*'
method: RequestMethod. ALL, GET, HEAD 등
*/
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerExpress) // 또는 LoggerFastify
.forRoutes({ path: '/api/*', method: RequestMethod.ALL })
}
}
참고 링크
https://docs.nestjs.com/techniques/logger
https://docs.nestjs.com/techniques/performance
'JavaScript > NestJS' 카테고리의 다른 글
[NestJS] TypeORM CRUD 생성하기 (User) (0) | 2023.08.21 |
---|---|
[NestJS] 환경 변수 (config) 사용하기 (0) | 2023.08.20 |
[NestJS] Jest 테스트하기 (0) | 2023.08.17 |
[NestJS] 경로 alias 설정하기 (0) | 2023.08.17 |
[NestJS] API 생성하기 (+ CORS) (0) | 2023.08.17 |