javascript sdk를 사용해 cloudwatch log insight를 사용하는 법을 정리한다.

코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var AWS = require('aws-sdk');

AWS.config.update({region: 'ap-northeast-2',credentials: {
accessKeyId: "",
secretAccessKey: "",
}, });

// Create CloudWatch service object
var cl = new AWS.CloudWatchLogs();

const params = {
startTime: new Date(2022,10,16,0,0,0).getTime(),/* required */
endTime: new Date(2022,10,17,0,0,0).getTime() /* required */ ,
logGroupName: '' /* required */ ,
queryString: `` /* query문 작성 */
}

cl.startQuery(params, (err, data) => {
if(err) {
console.log(err, err.stack);
} else {
const {queryId} = data;
cl.getQueryResults({queryId}, (_err, _data) => {
if (_err ) {
console.log(_err, _err.stack);
} else {
console.log(_data)
}
})
getResults(data)
}

})

const getResults = (data) => {
cl.getQueryResults({
queryId: data.queryId
}, (_err, _data) => {
if (_err) {
console.log(_err, _err.stack)
}
else {
if (_data.results) {
// do something
}

/*check the status and run the function again*/
if (_data.status.toLowerCase() === 'running') {
getResults(data)
}
}
})
}


참고