티스토리 뷰

이 페이지는 Node.js 프로젝트에 Amazon AWS CloudWatch 데이터를 가져오는 방법을 설명하고 있다.

 

코드설명에 앞서 CloudWatch에 대해 간단하게 설명하자면,

개발자 / 시스템 운영자 / 사이트 안정성 엔지니어 및 IT관리자를 위해 구축된 모니터링 및 관리 서비스이다.

 

CloudWatch도 Amazon서비스이기때문에 코드작성에 앞서 연결하는 작업이 필요하다

(아래 코드에서는 region, accessKeyId, secretAccessKey를 하드코딩이 아닌 환경변수에 저장해두고 가져오는 형태로 사용하였다)

const AWS = require('aws-sdk')
AWS.config.update({
    region: config.AWSRegion,
    accessKeyId : config.AWSAccessKeyId,
    secretAccessKey: config.AWSSecretAccessKey
});

 

아래는 CloudWatch의 지표 중 하나인 'NumberOfMessagesPublished' 데이터를 가져오는 코드이다

period(요청할시간)를 60이상으로 설정한 이유는, cloudWatch가 집계하는데 필요한 최소시간 단위가 1분이기 때문이다.

또 확인할 것은 params에 있는 항목의 Key는 첫글자가 대문자이고, 빠지는 항목없이 작성해주어야한다는 것!

 

const cw = new AWS.CloudWatch();

exports.getCloudWatch = async (req, res, next) => {
    let { startDate, endDate, period } = req.query;
    if (period < 60) period = 60;
    const StartTime = new Date(startDate).toISOString();
    const EndTime = new Date(`${endDate}T23:59:59`).toISOString();
	const params = {
    	Namespace: 'AWS/SNS',
        Statistics: ['Sum'],
        Unit: 'Count',
        Dimensions: [{ Name: 'TopicName', Value: `${TopicNameValue}` }],
        MetricName: 'NumberOfMessagesPublished',
        StartTime,
        EndTime,
        Period: period,
    };
    
    cw.getMetricStatistics(params, (err, data) => {
        if (err) return console.log(err);
        data.Datapoints.sort((a, b) => (a.Timestamp > b.Timestamp) ? 1 : ((a.Timestamp < b.Timestamp) ? -1 : 0 ));
        return res.send({ result: data });
    });
};

getMetricStatistics의 결과값에는 순서가 없이 뒤죽박죽 섞여있어, sort함수를 이용해 Timestamp기준 오름차순으로 정렬해주었다.

정렬된 최종 데이터는 다음과 같다 :)

"NumberOfMessagesPublished": {
	"ResponseMetadata": {
    	"RequestId": ""
    },
  	"Label": "NumberOfMessagesPublished",
    "Datapoints": [
      {
      	"Timestamp": "2019-03-28T00:00:00.000Z",
        "Sum": 1,
        "Unit": "Count"
      },
      {
        "Timestamp": "2019-03-28T00:10:00.000Z",
        "Sum": 6,
        "Unit": "Count"
      },
      {
        "Timestamp": "2019-03-28T00:20:00.000Z",
        "Sum": 3,
        "Unit": "Count"
      },
      {
        "Timestamp": "2019-03-28T00:25:00.000Z",
        "Sum": 2,
        "Unit": "Count"
      },  
      ... 생략
	]
}

 

댓글
최근에 올라온 글
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Total
Today
Yesterday