Azure Monitor 쿼리 메트릭 클라이언트 라이브러리는 Azure Monitor의 메트릭 데이터 플랫폼에 대해 읽기 전용 쿼리를 실행하는 데 사용됩니다.
- Metrics - 모니터링되는 리소스에서 시계열 데이터베이스로 숫자 데이터를 수집합니다. 메트릭은 정기적으로 수집되며 특정 시간에 시스템의 일부 측면을 설명하는 수치 값입니다. 메트릭은 가볍고 거의 실시간 시나리오를 지원할 수 있으므로 문제를 경고하고 빠르게 검색하는 데 유용합니다.
권고@azure/monitor-query에서 ⚠ 마이그레이션 ️
원래 패키지에서 라이브러리로 @azure/monitor-query 애플리케이션 코드를 업데이트하는 방법에 대한 자세한 지침은 @azure/monitor-query-metrics를 확인하세요.
리소스:
시작하기
지원되는 환경
- Node.js의 LTS 버전
- Safari, Chrome, Microsoft Edge 및 Firefox의 최신 버전
자세한 내용은 지원 정책을 참조하세요.
필수 조건
- Azure 서비스 구독
- TokenCredential 구현(예: Azure Identity 라이브러리 자격 증명 형식).
- 메트릭을 쿼리하려면 모든 종류의 Azure 리소스(스토리지 계정, Key Vault, Cosmos DB 등)가 필요합니다.
패키지 설치
npm을 사용하여 JavaScript용 Azure Monitor 쿼리 메트릭 클라이언트 라이브러리를 설치합니다.
npm install --save @azure/monitor-query-metrics
클라이언트 만들기
메트릭을 쿼리하려면 인증된 클라이언트가 필요합니다. 인증을 위해 다음 예제에서는 @azure/identity 패키지의 DefaultAzureCredential을 사용합니다.
import { DefaultAzureCredential } from "@azure/identity";
import { MetricsClient } from "@azure/monitor-query-metrics";
const credential = new DefaultAzureCredential();
// Create a MetricsClient
const endpoint = " https://<endpoint>.monitor.azure.com/";
const metricsClient = new MetricsClient(endpoint, credential);
Azure 소버린 클라우드에 대한 클라이언트 구성
기본적으로 라이브러리의 클라이언트는 Azure 퍼블릭 클라우드를 사용하도록 구성됩니다. 대신 소버린 클라우드를 사용하려면 클라이언트를 인스턴스화할 때 올바른 엔드포인트 및 대상 그룹 값을 제공합니다. 다음은 그 예입니다.
import { DefaultAzureCredential } from "@azure/identity";
import { MetricsClient } from "@azure/monitor-query-metrics";
const credential = new DefaultAzureCredential();
// Create a MetricsClient
const endpoint = " https://<endpoint>.monitor.azure.cn/";
const metricsClient = new MetricsClient(endpoint, credential, {
audience: "https://monitor.azure.cn/.default",
});
쿼리 실행
메트릭 쿼리의 예는 예제 섹션을 참조하세요.
주요 개념
메트릭 데이터 구조
각 메트릭 값 집합은 다음과 같은 특성을 가진 시계열입니다.
- 값이 수집된 시간
- 값과 연결된 리소스입니다.
- 메트릭의 범주처럼 작동하는 네임스페이스
- 메트릭 이름
- 값 자체
- 일부 메트릭에는 다차원 메트릭에 설명된 대로 여러 차원이 있습니다. 사용자 지정 메트릭에는 최대 10개의 차원이 있을 수 있습니다.
예시
메트릭 쿼리
하나 이상의 Azure 리소스에 대한 메트릭을 쿼리하려면 메서드를 queryResourcesMetricsClient사용합니다. 이 방법을 사용하려면 클라이언트를 만들 때 지역 엔드포인트가 필요합니다. 예: https://westus3.metrics.monitor.azure.com.
각 Azure 리소스는 다음 위치에 있어야 합니다.
- 클라이언트를 만들 때 지정된 엔드포인트와 동일한 지역입니다.
- 동일한 Azure 구독입니다.
리소스 ID는 메트릭이 쿼리되는 리소스의 ID여야 합니다. 일반적으로 형식입니다 /subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>.
리소스 ID/URI를 찾으려면 다음을 수행합니다.
- Azure Portal에서 리소스의 페이지로 이동합니다.
- 개요 섹션에서 JSON 보기 링크를 선택합니다.
- JSON 보기 맨 위에 있는 리소스 ID 텍스트 상자의 값을 복사합니다.
더욱이:
- 사용자는 Azure 구독 수준에서 모니터링 데이터를 읽을 수 있는 권한을 부여받아야 합니다. 예를 들어 쿼리할 구독에 대한 모니터링 읽기 권한자 역할이 있습니다.
- 쿼리할 메트릭을 포함하는 메트릭 네임스페이스를 제공해야 합니다. 메트릭 네임스페이스 목록은 리소스 유형별로 지원되는 메트릭 및 로그 범주를 참조하세요.
import { DefaultAzureCredential } from "@azure/identity";
import { MetricsClient } from "@azure/monitor-query-metrics";
const resourceIds = [
"/subscriptions/0000000-0000-000-0000-000000/resourceGroups/test/providers/Microsoft.OperationalInsights/workspaces/test-logs",
"/subscriptions/0000000-0000-000-0000-000000/resourceGroups/test/providers/Microsoft.OperationalInsights/workspaces/test-logs2",
];
const metricsNamespace = "Microsoft.OperationalInsights/workspaces";
const metricNames = ["Heartbeat"];
const endpoint = "https://westus3.metrics.monitor.azure.com";
const credential = new DefaultAzureCredential();
const metricsClient = new MetricsClient(endpoint, credential);
const result = await metricsClient.queryResources(resourceIds, metricNames, metricsNamespace, {
aggregation: "Count",
});
console.log(`Retrieved metrics for ${result.length} resources`);
for (const resource of result) {
console.log(`Resource: ${resource.resourceId}`);
console.log(`Metrics: ${resource.metrics.length}`);
}
메트릭 쿼리 응답 처리
메트릭 쿼리 API는 객체 목록을 MetricsQueryResult 반환합니다. 개체에는 MetricsQueryResult -typed 개체 목록 Metric, granularity, namespace및 timespan와 같은 속성이 포함되어 있습니다.
Metric 개체 목록은 속성을 사용하여 액세스할 수 있습니다metrics. 이 목록의 각 Metric 개체에는 개체 목록이 포함되어 있습니다 TimeSeriesElement . 각 TimeSeriesElement 개체에는 및 속성이 metadatavalues 포함됩니다data. 시각적 형식에서 응답의 개체 계층 구조는 다음 구조와 유사합니다.
MetricsQueryResult
|---granularity
|---timespan
|---cost
|---namespace
|---resourceRegion
|---metrics (list of `Metric` objects)
|---id
|---type
|---name
|---unit
|---timeseries (list of `TimeSeriesElement` objects)
|---metadatavalues
|---data (list of data points)
메모: 각각 MetricsQueryResult 은 매개 변수의 해당 리소스와 동일한 순서로 반환됩니다 resourceIds . 여러 다른 메트릭을 쿼리하면 전송된 순서 metricNames 대로 메트릭이 반환됩니다.
응답 처리 예:
import { DefaultAzureCredential } from "@azure/identity";
import { MetricsClient, Durations } from "@azure/monitor-query-metrics";
const resourceIds = [
"/subscriptions/0000000-0000-000-0000-000000/resourceGroups/test/providers/Microsoft.OperationalInsights/workspaces/test-logs",
];
const metricsNamespace = "Microsoft.OperationalInsights/workspaces";
const metricNames = ["Heartbeat"];
const endpoint = "https://westus3.metrics.monitor.azure.com";
const credential = new DefaultAzureCredential();
const metricsClient = new MetricsClient(endpoint, credential);
const endTime = new Date();
const startTime = new Date(endTime.getTime() - 60 * 60 * 1000); // 1 hour ago
const result = await metricsClient.queryResources(resourceIds, metricNames, metricsNamespace, {
aggregation: "Count,Average", // Multiple aggregations
startTime: startTime,
endTime: endTime,
interval: Durations.fiveMinutes,
top: 10, // Limit results
orderBy: "count desc", // Sort by count descending
filter: "Computer eq '*'", // Filter criteria
});
console.log(`Retrieved ${result.length} resources with advanced filtering`);
for (const resource of result) {
for (const metric of resource.metrics) {
console.log(`Metric: ${metric.name}`);
console.log(`Time series count: ${metric.timeseries.length}`);
}
}
각 Azure 리소스 종류에 사용할 수 있는 메트릭 및 차원의 인벤토리는 Azure Monitor에서 지원되는 메트릭을 참조하세요.
문제 해결
다양한 오류 시나리오를 진단하려면 문제 해결 가이드를 참조하세요.
다음 단계
Azure Monitor에 대한 자세한 내용은 Azure Monitor 서비스 설명서를 참조하세요.
기여하기
이 라이브러리에 기여하려면 기여 가이드 읽어 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.
이 모듈의 테스트는 라이브 테스트와 단위 테스트가 혼합되어 있으므로 Azure Monitor 인스턴스가 있어야 합니다. 테스트를 실행하려면 다음을 실행해야 합니다.
rush updaterush build -t @azure/monitor-query-metricscd into sdk/monitor/monitor-query-metrics-
sample.env파일을 복사 합니다..env - 편집기에서 파일을
.env열고 값을 입력합니다. -
npm run test;
자세한 내용은 테스트 폴더를 참조하십시오.
관련 프로젝트
- JavaScript용 Microsoft Azure SDK
- Azure Monitor
Azure SDK for JavaScript