다음을 통해 공유


데이터 API 작성기에서 Azure Application Insights 사용

Azure Application Insights는 요청, 추적, 예외 및 성능 메트릭을 자동으로 캡처하는 APM(애플리케이션 성능 모니터링) 서비스입니다. DAB(Data API Builder)와 통합하면 런타임 동작을 모니터링하고, 문제를 진단하고, 프로덕션 환경에서 성능을 최적화할 수 있습니다.

Application Insights 원격 분석 흐름을 보여 주는 다이어그램.

경고

DAB와 Application Insights 통합은 이중 계측으로 인해 Azure App Service 웹앱에서 호스트되는 경우 제한 사항이 있을 수 있습니다. Application Insights는 컨테이너, Azure Container Apps 또는 AKS(Azure Kubernetes Service)에서 자체 호스팅할 때 DAB에서 가장 잘 작동합니다. App Service를 사용해야 하는 경우 철저히 테스트하거나 대체 모니터링 방법을 고려합니다.

필수 조건

  • 기존 DAB 구성 파일입니다.
  • Azure Application Insights 리소스.
  • Application Insights 연결 문자열입니다.
  • 데이터 API 작성기 CLI. CLI 설치

연결 문자열 가져오기

DAB를 구성하기 전에 Azure에서 Application Insights 연결 문자열을 가져옵니다.

Azure 포털

  1. Azure Portal에서 Application Insights 리소스로 이동합니다.
  2. 개요 또는 속성으로 이동합니다.
  3. 연결 문자열(계측 키가 아님)을 복사합니다.

Azure 커맨드 라인 인터페이스 (CLI)

az monitor app-insights component show \
  --app my-app-insights \
  --resource-group my-rg \
  --query connectionString -o tsv

연결 문자열 형식

InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://<region>.in.applicationinsights.azure.com/;LiveEndpoint=https://<region>.livediagnostics.monitor.azure.com/

비고

지역별 엔드포인트 및 성능 향상을 위해 전체 연결 문자열(계측 키뿐만 아니라)을 사용합니다.

Application Insights를 구성하기

application-insights 구성 파일 아래에 runtime.telemetry 섹션을 추가합니다.

{
  "runtime": {
    "telemetry": {
      "application-insights": {
        "enabled": true,
        "connection-string": "@env('app-insights-connection-string')"
      }
    }
  }
}

이 구성은 연결 문자열에 환경 변수를 사용합니다. ".env 파일에 정의합니다."

app-insights-connection-string="InstrumentationKey=...;IngestionEndpoint=...;LiveEndpoint=..."

경고

연결 문자열을 소스 제어에 커밋하지 않습니다. 항상 환경 변수 또는 Azure Key Vault를 사용합니다.

Command-line

Application Insights를 dab add-telemetry을 통해 구성합니다.

Option 설명
--app-insights-enabled Application Insights(true 또는)를 사용하거나 false사용하지 않도록 설정합니다.
--app-insights-conn-string Application Insights에 대한 연결 문자열입니다.

Application Insights 사용

dab add-telemetry \
  --app-insights-enabled true \
  --app-insights-conn-string "@env('app-insights-connection-string')"

Application Insights를 사용하지 않도록 설정

dab add-telemetry \
  --app-insights-enabled false

비고

Application Insights 설정은 dab add-telemetry, dab configure가 아닙니다.

DAB 실행

구성 파일로 DAB를 시작합니다.

dab start

시작 로그에서 확인을 확인합니다.

Application Insights telemetry is enabled with connection string from config.

작동 방식

Application Insights를 활성화하면 DAB:

  1. AddApplicationInsightsTelemetry()를 사용하여 Application Insights SDK를 등록합니다.
  2. 사용자 지정 원격 분석 이니셜라이저를 등록하여 DAB 관련 속성을 사용하여 모든 원격 분석을 보강합니다.
  3. TelemetryClient를 구성 파일의 연결 문자열로 설정합니다.
  4. ASP.NET Core 로깅과 통합하여 콘솔 로그를 추적으로 캡처합니다.

데이터 흐름

DAB Application
    ↓
ILogger (ASP.NET Core)
    ↓
ApplicationInsightsLoggerProvider
    ↓
AppInsightsTelemetryInitializer (adds custom properties)
    ↓
TelemetryClient
    ↓
Application Insights (Azure)

캡처되는 항목

원격 분석 유형 출처 예시
요청 ASP.NET Core 미들웨어 REST/GraphQL 요청, 응답 시간, 상태 코드
Traces ILogger DAB에서의 통화 시작 로그, 쿼리 실행 로그, 경고
Exceptions 처리되지 않은 예외 런타임 오류, 구성 오류, 데이터베이스 오류
종속성 데이터베이스 호출 SQL 쿼리, Azure Cosmos DB 작업, 기간
성능 계수기 실행 시간 CPU 사용량, 메모리 사용량, 요청 속도

원격 분석 강화

DAB는 사용자 지정 속성을 사용하여 모든 Application Insights 원격 분석을 자동으로 보강합니다.

재산 설명 예제 값
ProductName DAB 사용자 에이전트 식별자 dab-1.2.3
UserAgent 전체 DAB 사용자 에이전트 문자열 data-api-builder/1.2.3
Cloud.RoleName DAB 클라우드 역할 이름 DataApiBuilder
Component.Version DAB 버전 1.2.3
Session.Id 고유 세션 식별자 guid

이러한 속성은 Application Insights에서 DAB 관련 원격 분석을 필터링하고 상호 연결하는 데 도움이 됩니다.

Azure에서 원격 분석 데이터 쿼리

추적(로그)

traces
| where customDimensions["ProductName"] startswith "dab-"
| order by timestamp desc
| project timestamp, message, severityLevel

LogLevel 매핑:

로그레벨 심각도 가치
추적/디버그 장황한 0
정보 정보 1
경고 경고 2
오류 오류 3
중요한 중요한 4

요청

requests
| where customDimensions["ProductName"] startswith "dab-"
| order by timestamp desc
| project timestamp, name, duration, resultCode, success

Application Insights의 Data API Builder 애플리케이션 요청에 대한 쿼리 결과의 스크린샷.

Exceptions

exceptions
| where customDimensions["ProductName"] startswith "dab-"
| order by timestamp desc
| project timestamp, type, outerMessage, details

Application Insights의 데이터 API 작성기 예외에 대한 쿼리 결과 스크린샷.

DAB 버전별 필터링

traces
| where customDimensions["Component.Version"] == "1.2.3"
| project timestamp, message, severityLevel

느린 GraphQL 쿼리 찾기

requests
| where name contains "/graphql"
| where duration > 1000
| project timestamp, name, duration, resultCode
| order by duration desc

요청 성공률

requests
| where customDimensions["ProductName"] startswith "dab-"
| summarize 
    Total = count(),
    Success = countif(success == true),
    Failed = countif(success == false)
| extend SuccessRate = (Success * 100.0) / Total

가장 느린 데이터베이스 작업

dependencies
| where type == "SQL" or type == "Azure Cosmos DB"
| top 10 by duration desc
| project timestamp, name, duration, target, data

실시간 지표

라이브 메트릭은 1초 대기 시간으로 실시간 모니터링 <을 제공합니다. Application Insights가 구성되면 자동으로 사용하도록 설정됩니다.

라이브 메트릭에 액세스

  1. Azure Portal에서 Application Insights 리소스를 엽니다.
  2. 왼쪽 메뉴에서 라이브 메트릭 으로 이동합니다.
  3. DAB 애플리케이션을 시작합니다.
  4. 몇 초 내에 실시간 데이터가 나타납니다.

Application Insights의 Data API Builder 데이터에 대한 라이브 메트릭 페이지의 스크린샷.

표시되는 내용

Metric 설명
들어오는 요청 초당 REST/GraphQL 요청 수
발신 요청 초당 데이터베이스 호출 수
전체 상태 성공률, 초당 실패 수
메모리/CPU 리소스 사용량
예외 비율 초당 예외 수

팁 (조언)

개발 중에 라이브 메트릭을 사용하여 API 요청 및 데이터베이스 작업에 대한 즉각적인 피드백을 확인합니다.

샘플링 및 데이터 보존

적응 샘플링

Application Insights SDK는 볼륨이 높을 때 원격 분석을 자동으로 샘플링하여 비용을 절감하고 속도 제한을 유지합니다. 샘플링 속도는 Application Insights UI에 표시됩니다.

기본 동작:

  • 트래픽 저하: 전송된 모든 원격 분석(100%)
  • 높은 트래픽: 샘플링은 볼륨을 자동으로 줄입니다.
  • 유지 관리되는 대표 데이터

데이터 보존

Plan 기본 보존 최대 보존 기간
무료 요금제 90일 90일
Pay-as-you-go 90일 730일(2년)

보존 구성: Application Insights → 사용량 및 예상 비용데이터 보존.

성능 고려 사항

원격 분석 부하

Application Insights는 최소한의 오버헤드를 추가합니다.

  • 메모리: 트래픽에 따라 10~50MB
  • CPU: <정상 부하에서 1%
  • 대기 시간: <요청당 1ms(비동기)

모범 사례

  • 연결 문자열에 환경 변수를 사용합니다.
  • 필요하지 않은 경우 로컬 개발에서 사용하지 않도록 설정합니다.
  • 프로덕션 환경에서 샘플링 속도를 모니터링합니다.
  • 적절한 데이터 보존을 설정하여 비용을 관리합니다.

개발 중 사용 안 함

{
  "runtime": {
    "telemetry": {
      "application-insights": {
        "enabled": false
      }
    }
  }
}

내보내기 및 시각화

원격 분석은 Application Insights SDK를 사용하여 내보내집니다. SDK는 데이터를 정기적으로 일괄 처리하고 보냅니다.

비고

SDK는 내보내기 타이밍을 제어합니다. 기본 동작은 몇 초마다 일괄적으로 원격 분석을 보냅니다.

경고

빠르게 종료되는 임시 컨테이너는 내보내기가 완료되기 전에 종료될 수 있습니다. 우아한 종료 창을 구성하고 적극적인 종료를 방지하여 보류 중인 원격 분석 데이터의 플러시가 완료되도록 보장하십시오.

연결 문자열 대 계측 키

{
  "connection-string": "InstrumentationKey=...;IngestionEndpoint=https://eastus.in.applicationinsights.azure.com/"
}

이점:

  • 지역별 엔드포인트(짧은 대기 시간)
  • 주권 클라우드 지원
  • 미래 방지(Microsoft의 권장 방법)

레거시 계측 키

Microsoft는 계속 지원하고 있지만 새 구현에는 연결 문자열을 사용하는 것을 권장합니다.

{
  "connection-string": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
}

비고

계측 키만 제공하는 경우 Application Insights는 대기 시간이 더 긴 전역 수집 엔드포인트를 사용합니다.

Troubleshooting

오류: "사용하도록 설정된 경우 Application Insights 연결 문자열은 null이거나 비워 둘 수 없습니다."

원인: enabled 설정 true 되었지만 connection-string 누락되었거나 비어 있습니다.

해결 방법: Application Insights를 사용하도록 설정할 때 유효한 연결 문자열을 제공하거나 다음으로 enabled설정합니다false.

{
  "runtime": {
    "telemetry": {
      "application-insights": {
        "enabled": true,
        "connection-string": "@env('app-insights-connection-string')"
      }
    }
  }
}

DAB가 시작되지만 원격 분석이 나타나지 않음

다음 메시지에 대한 시작 로그를 확인합니다.

dab start --LogLevel Information

성공 메시지:

Application Insights telemetry is enabled with connection string from config.

경고 메시지:

Logs won't be sent to Application Insights because an Application Insights connection string is not available in the runtime config.
Application Insights are disabled.

오류 메시지:

Telemetry client is not initialized.

환경 변수 확인

echo $app-insights-connection-string

직접 연결 문자열로 테스트

일시적으로 직접 연결 문자열(환경 변수 아님)을 사용하여 문자열이 유효한지 확인합니다.

{
  "connection-string": "InstrumentationKey=...;IngestionEndpoint=..."
}

이 작업이 작동하면 환경 변수 로드와 관련된 문제가 발생합니다.