사용할 로그 레벨별 메세지 서비스 작성 및 모듈작성

logger.service.ts

import { ConsoleLogger, Injectable } from '@nestjs/common';

@Injectable()
export class LoggerService extends ConsoleLogger {

  log(message: any, ...optionalParams: any[]) {
    super.log(`${message}`, ...optionalParams);
  }

  error(message: any, ...optionalParams: any[]) {
    super.error(` ${message}`, ...optionalParams);
  }

  warn(message: any, ...optionalParams: any[]) {
    super.warn(` ${message}`, ...optionalParams);
  }

  debug(message: any, ...optionalParams: any[]) {
    super.debug(`${message}`, ...optionalParams);
  }
}

 

logger.module.ts

import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';

@Module({
  providers: [LoggerService],
  exports: [LoggerService],
})
export class LoggerModule {}

 

메인에 설정

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe } from '@nestjs/common';
import { initializeTransactionalContext } from 'typeorm-transactional';
// 추가된 코드
import { LoggerService } from './common/Logger/logger.service';

async function bootstrap() {
  initializeTransactionalContext();
  const app = await NestFactory.create(AppModule, { bufferLogs: true });// 로그설정
  app.useLogger(app.get(LoggerService));// 서비스 설정
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    }),
  );
  const configService = app.get(ConfigService);
  const port = configService.get<string>('PORT') as string;
  const hostIP = configService.get<string>('HOST_IP') as string;
  await app.listen(port, hostIP);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();

 

 

app api 에 적용

app.controller.ts

import ....

@Controller('routines')
export class RoutineController {
  // 로그 헤더에 표시됨 -> [AppController] (message)
  // 해당 컨트롤러에 맞게 변경
  private readonly logger = new Logger(AppController.name); 
  constructor(private readonly routineService: RoutineService) {}


  @Get()
  @UseGuards(JwtAuthGuard)
  getRoutine(@Body() getRoutineRequest: GetRoutineRequestDto, @Request() req: any) {
    this.logger.log(`start getRoutine DTO : ${getRoutineRequest.name}`); // 로그 생성
    return this.routineService.getRoutineByName(getRoutineRequest, req.user);
  }
  ...
}

 

app.service.ts

import ...

@Injectable()
export class AppService {
  // 해당 서비스에 맞게 변경 ex)PostService.name
  private readonly logger = new Logger(AppService.name);
  constructor(
  	....
  ) {}


  async getRoutineByName(getRoutineRequest: GetRoutineRequestDto, user: User) {
    const { name } = getRoutineRequest;
    const routines = await this.routineRepository.findOne({where:{name}});
    if(!routines){
       this.logger.log(`Routines using name:'${name}' can not find`);
       throw new BadRequestException(`Routines using name:'${name}' can not find`);
    }
   
    this.logger.log(`found routines using ${name}`);
    return routines;
  }

}

 

 

참고자료

https://docs.nestjs.com/techniques/logger

+ Recent posts