AngularJS/SPA 애플리케이션에서 Application Insights 이용하기

Application Insights 는 일반적으로 웹 애플리케이션의 성능 혹은 예외정보와 같은 유용한 정보를 자동적으로 수집함으로써 웹 애플리케이션을 모니터링 할 수 있습니다. 또한, Application Insights를 page script에 간단히 추가함으로써 페이지로드 및 AJAX 호출 시간, 브라우저 예외 및 AJAX 실패의 수 및 세부 사항등에 대한 모니터링 정보를 얻을 수 있습니다.

다음은 AngularJS/SPA를 위한 Application Insights의 사용방법에 대한 소개입니다. 해당 방법은 https://ngmodules.org/modules/angular-appinsights 에서 제공되는 AppInsights와 관련한 Angular 모듈과 https://www.c-sharpcorner.com/article/single-page-application-using-web-api-and-angularjs 에서 제공되는 AngularJS/SPA 샘플코드를 이용해서 설정 가이드 합니다.

먼저, Azure Subscription이 있다면 Azure 포탈(https://portal.azure.com/#create/hub)에서 Monitoring+Management 를 선택하고 Application Insights를 선택하여 Application insights 리소스를 생성합니다.

생성한 Application Insights portal 로 들어가서 “getting started” 들어갑니다. 그리고, “monitor and diagnose client side application”을 선택하면, 아래의 이미지와 같이 page script에 추가할 AppInsights 관련 script code를 얻을 수 있습니다.

 

상위의 site에서 얻어진 script 코드를 copy하여 우선 AppInsights.js라는 이름으로 파일생성합니다. 이때, instrumentationKey:" < 키 생략> " 코드 부분은 삭제합니다.

그리고 https://ngmodules.org/modules/angular-appinsights 에서 제공하는 angular-appinsights.js 를 download 합니다.

해당 두 script code는 아래와 같이 적절한 위치에 포함합니다. 예를 들어, https://www.c-sharpcorner.com/article/single-page-application-using-web-api-and-angularjs/ 예제에서는 Views\index.html의 head tag안에 script tag를 이용하여 포함합니다.

 <script src="../Scripts/AppInsights.js"></script>

<script src="../Scripts/angular-appinsights.js"></script> 

이후에 해당 application bootstrap 안에 angular-appinsights 를 초기화 합니다. 아래의 예는 SPA예제코드의 theMusic.js 파일안에서 angular-appinsights를 위해 추가된 코드를 빨간 블럭으로 표시했습니다.

중요한 것은 insightsProvider.start(); 에 parameter로 전달하는 값이 application insights azure portal에서 제공하는 instrumentationKey 입니다. 이는 application insights azure portal안에 properties 메뉴에서 얻을 수 있습니다.

이와 같이 angular-appinsights가 초기화되었다면, SPA관련 controller 마다 insightsProvider가 제공하는 trackPageView() 를 호출함으로써 간단하게 Page View load time 로그를 전송할 수 있습니다. 아래의 예는 SPA 예제코드의 detailscontroller.js 파일안에서 trackPageView()를 호출하는 코드를 빨간 블럭으로 표시했습니다.

지금까지 정상적으로 설정이 되었다면, 해당 AngularJS/SPA 애플리케이션에서 navigation을 할 경우에 설정되어 있는 trackPageView() 함수가 로그를 Application Insights portal 로 전송할 것입니다. 이를 확인하기 위해서 Application Insights Azure Portal에서 browser 메뉴를 선택하면 다음과 같은 Page View 화면을 볼 수 있습니다.

자세히 살펴보면, 앞에서 AppInsights를 추가한 DetailsController와 관련한 page view load time이 기록되는 것을 확인할 수 있습니다.