다음을 통해 공유


Application Insights를 사용하여 요청을 추적하는 코드 작성

Application Insights는 Azure Portal의 성능 페이지에서 애플리케이션에 대한 프로필을 제공하기 위해 애플리케이션에 대한 요청을 추적해야 합니다. 이미 계측된 프레임워크(예: ASP.NET 및 ASP.NET Core)에 빌드된 애플리케이션의 경우 Application Insights는 요청을 자동으로 추적할 수 있습니다.

Azure Cloud Services 작업자 역할 및 Azure Service Fabric 상태 비저장 API 등의 다른 애플리케이션의 경우, 요청이 시작되고 끝나는 위치를 Application Insights에 알려주는 코드를 사용하여 요청을 추적해야 합니다. 그러면 요청 원격 분석이 성능 페이지에서 볼 수 있는 Application Insights로 전송됩니다. 이러한 요청에 대한 프로필이 수집됩니다.

요청을 수동으로 추적하려면 다음을 수행합니다.

  1. 애플리케이션 수명 초기에 다음 코드를 추가합니다.

    using Microsoft.ApplicationInsights.Extensibility;
    ...
    // Replace with your own Application Insights instrumentation key.
    TelemetryConfiguration.Active.InstrumentationKey = "00000000-0000-0000-0000-000000000000";
    

    이 전역 계측 키 구성에 대한 자세한 내용은 Application Insights를 통해 Service Fabric 사용을 참조하세요.

  2. 계측하려는 코드 조각의 경우 다음 예제와 같이 StartOperation<RequestTelemetry>using 문을 추가합니다.

    using Microsoft.ApplicationInsights;
    using Microsoft.ApplicationInsights.DataContracts;
    ...
    var client = new TelemetryClient();
    ...
    using (var operation = client.StartOperation<RequestTelemetry>("Insert_Your_Custom_Event_Unique_Name"))
    {
      // ... Code I want to profile.
    }
    

    다른 StartOperation<RequestTelemetry> 범위 내의 StartOperation<RequestTelemetry> 호출은 지원되지 않습니다. 대신, 중첩된 범위에서는 StartOperation<DependencyTelemetry>를 사용할 수 있습니다. 예시:

    using (var getDetailsOperation = client.StartOperation<RequestTelemetry>("GetProductDetails"))
    {
    try
    {
      ProductDetail details = new ProductDetail() { Id = productId };
      getDetailsOperation.Telemetry.Properties["ProductId"] = productId.ToString();
    
      // By using DependencyTelemetry, 'GetProductPrice' is correctly linked as part of the 'GetProductDetails' request.
      using (var getPriceOperation = client.StartOperation<DependencyTelemetry>("GetProductPrice"))
      {
          double price = await _priceDataBase.GetAsync(productId);
          if (IsTooCheap(price))
          {
              throw new PriceTooLowException(productId);
          }
          details.Price = price;
      }
    
      // Similarly, note how 'GetProductReviews' doesn't establish another RequestTelemetry.
      using (var getReviewsOperation = client.StartOperation<DependencyTelemetry>("GetProductReviews"))
      {
          details.Reviews = await _reviewDataBase.GetAsync(productId);
      }
    
      getDetailsOperation.Telemetry.Success = true;
      return details;
    }
    catch(Exception ex)
    {
      getDetailsOperation.Telemetry.Success = false;
    
      // This exception gets linked to the 'GetProductDetails' request telemetry.
      client.TrackException(ex);
      throw;
    }
    }
    

참고 항목

2025년 3월 31일에 계측 키 수집에 대한 지원이 종료됩니다. 계측 키 수집은 계속 작동하지만 더 이상 기능에 대한 업데이트 또는 지원을 제공하지 않습니다. 연결 문자열로 전환하여 새로운 기능을 활용합니다.

다음 단계

Application Insights Profiler 문제를 해결합니다.