투케이2K

495. (javaScript) 자바스크립트 AWS CloudWatch 특정 로그 그룹안에 존재하는 로그 스트림 목록 조회 수행 - DescribeLogStreams 본문

JavaScript

495. (javaScript) 자바스크립트 AWS CloudWatch 특정 로그 그룹안에 존재하는 로그 스트림 목록 조회 수행 - DescribeLogStreams

투케이2K 2026. 2. 24. 20:34
728x90
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : JavaScript (자바스크립트) / AWS / CloudWatch / DescribeLogStreams


- 사전) AWS CloudWatch 간단 설명 : 

  >> Aws CloudWatch 는 Amazon Web Services (AWS) 리소스 및 AWS 에서 실행되는 애플리케이션을 실시간으로 모니터링 할 수 있는 서비스입니다

  >> Aws CloudWatch 를 사용하면 시스템 전체의 리소스 사용률, 애플리케이션 성능, 운영 상태를 파악할 수 있습니다

  >> Aws CloudWatch 와 함께 사용할 수 있는 서비스 : 

    - Amazon Simple Notification Service (Amazon SNS) : CloudWatch 와 함께 Amazon SNS를 사용하여 구독 중인 엔드포인트 또는 클라이언트에 메시지를 전달 또는 전송하는 것을 조정하고 관리합니다

    - Amazon EC2 Auto Scaling : Amazon EC2 Auto Scaling 과 함께 CloudWatch 경보를 사용하여 사용자 정의 정책, 상태 확인, 일정에 따라 Amazon EC2 인스턴스를 자동으로 시작하거나 종료할 수 있습니다

    - AWS CloudTrail : AWS CloudTrail 을 사용해 AWS Management Console, AWS CLI 및 기타 서비스에서 수행한 호출을 포함하여 계정의 Amazon CloudWatch API에 대한 호출을 모니터링할 수 있습니다    

    - AWS Identity and Access Management (IAM) : IAM 을 사용하여 AWS 리소스를 사용할 수 있는 사용자를 제어(인증)하고 해당 사용자가 사용할 수 있는 리소스 및 사용 방법을 제어(권한 부여)할 수 있습니다

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko">
<head>
    <title>javaScriptTest</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">


    <!-- 반응형 구조 만들기 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">


    <!-- 내부 CSS 스타일 지정 -->
    <style>

        html, body {
            width: 100%;
            height: 100%;
            margin : 0 auto;
            padding : 0;
            border : none;
            background-color: #666;
        }

    </style>





    <!-- [CDN 주소 설정] -->
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1416.0.min.js"></script>






    <!-- [자바스크립트 코드 지정] -->
    <script>

        // --------------------------------------------------------------------------------------------------------------

        // [AWS 인증 변수 선언]        
        const accessKey = 'AK..A6';
        const secretKey = 'mP..5J';
        const region = 'ap-northeast-2';


        // [필요 변수 선언]
        const logGroupName = '/aws/lambda/device-queue-manager';

        var continueSelect = null;
        var innerFunction = null;
        const selectAllList = [];

        // --------------------------------------------------------------------------------------------------------------

        // [html 최초 로드 및 이벤트 상시 대기 실시]
        window.onload = async function() {
          console.log("");
          console.log("=========================================");
          console.log("[window onload] : [start]");
          console.log("=========================================");
          console.log("");

          try {

            // -----------------------------------------
            // [초기 변수 초기화]
            // -----------------------------------------
            continueSelect = null;
            innerFunction = null;
            selectAllList.length = 0;


            // -----------------------------------------
            // [AWS.config 지정]
            // -----------------------------------------       
            AWS.config.update({
              region: region,          
              accessKeyId: accessKey,
              secretAccessKey: secretKey
            });


            // -----------------------------------------
            // [AWS 객체 생성]
            // -----------------------------------------
            const aws = new AWS.CloudWatchLogs();


            // -----------------------------------------
            // [내부 함수 생성]
            // -----------------------------------------
            innerFunction = async function() {

              try {
                
                while (true) { // 반복 조회 수행

                  // -----------------------------------------
                  // [요청 파라미터 생성]
                  // -----------------------------------------
                  var param = null;

                  if (continueSelect != null && continueSelect != undefined && continueSelect != ''){
                    param = {
                      logGroupName: logGroupName, // 로그 그룹 명칭                     
                      orderBy: 'LastEventTime', // 'LogStreamName'도 가능
                      descending: true, // 최근 이벤트 순으로 내림차순                 
                      limit: 50, // 한번에 조회할 제한 개수
                      //nextToken : continueSelect // ✅ 반복 조회 요청
                    };
                  }
                  else {

                  else {
                    param = {
                      logGroupName: logGroupName, // 로그 그룹 명칭                     
                      orderBy: 'LastEventTime', // 'LogStreamName'도 가능
                      descending: true, // 최근 이벤트 순으로 내림차순
                      limit: 50, // 한번에 조회할 제한 개수
                    };
                  }


                  // -----------------------------------------
                  // Aws CloudWatch Logs 로그 그룹에 대한 정보 조회 수행
                  // -----------------------------------------
                  // AWS 참고 사이트 : https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogStreams.html
                  // -----------------------------------------       
                  const [err, res] = await aws.describeLogStreams(param).promise()
                    .then(data => [null, data])
                    .catch(error => [error, null]);

                  if (err) {
                    console.error("[aws result] : [Error] : ", err);

                    // [반복 조회 종료 위한 값 초기화]
                    continueSelect = null;

                  } else {
                    console.log("[aws result] : [Success] : ", JSON.stringify(res));

                    // ---------------------------------------------
                    // [로그 출력 예시 첨부]
                    // ---------------------------------------------
                    /*                     
                    {
                      "logStreams": [
                        {
                          "logStreamName": "20150531",
                          "creationTime": 1433189871774,
                          "arn": "arn:aws:logs:region:acct:log-group:my-logs:log-stream:20150531",
                          "storedBytes": 0
                        }
                      ],
                      "nextToken": "..."
                    }
                    */              
                    // ---------------------------------------------


                    // ---------------------------------------------
                    // [배열에 리스트 정보 추가]
                    // ---------------------------------------------
                    const resList = res.logStreams;

                    if (resList != null && resList != undefined){
                      selectAllList.push(...resList); // ✅ Array Add List
                    }
                    

                    // ---------------------------------------------
                    // [반복 조회에 사용 될 정보가 있는지 확인]
                    // ---------------------------------------------
                    const resNext = res.nextToken;
                    if (resNext != null && resNext != undefined && resNext != ''){
                      continueSelect = resNext; // ✅ Set 
                    }
                    else {
                      continueSelect = null; // Clear 
                    }

                  }


                  // ---------------------------------------------
                  // [반복 조회에 사용 될 정보가 있는지 확인 후 무한 루프 탈출 수행]
                  // ---------------------------------------------
                  if (continueSelect == null || continueSelect == undefined || continueSelect == ''){
                    console.error("[innerFunction] : [continueSelect] : Is Null >> Stop While True");
                    break;
                  }
                  else {
                    console.warn("[innerFunction] : [continueSelect] : Exists >> Go To While True");
                  }

                }


                console.log("");
                console.log("=========================================");
                console.log("[innerFunction] : Result");
                console.log("---------------------------------------");
                console.log("Length : ", selectAllList.length);
                console.log("---------------------------------------");
                console.log(JSON.stringify(selectAllList));
                console.log("=========================================");
                console.log("");

              }
              catch(exception){
                console.error("[innerFunction] : [Exception] : ", exception);
              }

            };



            // -----------------------------------------
            // [내부 클로저 함수 호출]
            // -----------------------------------------
            await innerFunction();


            // ---------------------------------------------
            // [Body 표시 JSON]
            // ---------------------------------------------
            var resJson = {
              response: "result",
              data: selectAllList
            }
            // ---------------------------------------------


            // ---------------------------------------------
            // [로그 출력]
            // ---------------------------------------------
            document.write(JSON.stringify(resJson));
            // ---------------------------------------------


          }
          catch (exception) {
            console.error("");
            console.error("=========================================");
            console.error("[window onload] : [Exception] : 예외 상황 발생");
            console.error("-----------------------------------------");
            console.error(exception);
            console.error("=========================================");
            console.error("");

            // ---------------------------------------------
            // [Body 표시 JSON]
            // ---------------------------------------------
            var errJson = {
              response: "exception",
              data: exception.message
            }
            // ---------------------------------------------


            // ---------------------------------------------
            // [에러 출력]
            // ---------------------------------------------
            document.write(JSON.stringify(errJson));
            // ---------------------------------------------

          }

        };

        // --------------------------------------------------------------------------------------------------------------

    </script>


</head>


<body>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

[Amazon 모니터링 및 로깅 서비스] AWS CloudWatch 와 CloudTrail 차이점 정리

https://kkh0977.tistory.com/8143

https://blog.naver.com/kkh0977/223934869835?trackingCode=blog_bloghome_searchlist


[자바스크립트 AWS Lambda 함수 목록 리스트 조회 수행 - ListFunctions]

https://kkh0977.tistory.com/8645

https://blog.naver.com/kkh0977/224190780409


[AWS Lambda] Aws 람다 Python 3.13 기반 기본 함수 구조 설명 정리

https://kkh0977.tistory.com/8188

https://blog.naver.com/kkh0977/223962723156?trackingCode=blog_bloghome_searchlist


[Aws Lambda] Aws 사이트에서 생성 된 Lambda 람다 검증 함수 리스트 및 내용 소스 코드 확인 방법

https://blog.naver.com/kkh0977/223765198383


[AWS] Lambda 람다 함수 수행 errorType Sandbox.Timedout 에러 발생

https://blog.naver.com/kkh0977/223962778768

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments