삽집하는 개발들/NodeJS

[NestJs] logger + cloudwacth 연동하기

악투 2023. 10. 21. 22:59
반응형

회사에서 실시간 로그 관련해서 작업을 하게 되었다.

 

기존 API에 로그 쌓는 것이 없었던 것... 충격!!!

 

sentry와 연동 하기 위해서 결제 및 승인을 받아야해서...

 

먼저 이미 쓰고 있는 cloudwatch에 로그를 연동하려고 작업 했다.

 

NestJS app.module.ts에서

 

onModuleInit (모듈의 종속성 처리 후 호출 되게 된다.) 참고 https://docs.nestjs.com/fundamentals/lifecycle-events

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

AWS 쪽에서도 몇가지 해줘야할 게 있지만... 다음에 설명하겠다.

 // log Stream 체크
  // 모듈의 종속성 처리 후 호출
  async onModuleInit() {
    let logStreamName: string = process.env.MODE == 'dev' ? 'team-logs' : 'team-logs-live';
    global.logStreams = '';

    let cloudWatchLogs = new CloudWatchLogs({
      region: 'ap-northeast-2',
      accessKeyId: process.env.AWS_CW_ACCESS_KEY,
      secretAccessKey: process.env.AWS_CW_SECRET_KEY,
    });
    global.cloudWatchLogs = cloudWatchLogs;

    // 최초 로그 스트림 체크 하여 전역변수에 저장
    cloudWatchLogs
      .describeLogStreams({
        logGroupName: logStreamName,
        descending: true,
        orderBy: 'LogStreamName',
        limit: 1,
      })
      .promise()
      .then((data) => {
        global.logStreams = data.logStreams.length != 0 ? data.logStreams[0].logStreamName : '';
      })
      .catch((err) => {
        console.log(err);
      });
  }

 

 

반응형

'삽집하는 개발들 > NodeJS' 카테고리의 다른 글

[nodejs]CLI 만들기  (191) 2023.09.30