azure-mgmt-applicationinsights-dotnet
microsoft/skills
.NET SDK를 사용하여 구성 요소, 웹 테스트, 워크북 및 API 키를 포함한 Azure Application Insights 리소스를 관리합니다.
...모든 것을 확장하십시오Azure.ResourceManager.ApplicationInsights (.NET)
애플리케이션 성능 모니터링을 위한 Application Insights 리소스를 관리하는 Azure Resource Manager SDK입니다.
설치
dotnet add package Azure.ResourceManager.ApplicationInsights
dotnet add package Azure.Identity
현재 버전: v1.0.0 (GA)
API 버전: 2022-06-15
환경 변수
AZURE_SUBSCRIPTION_ID= # 필수: Azure 구독 ID
AZURE_SUBSCRIPTION_ID= # 필수: Azure 구독 ID
AZURE_RESOURCE_GROUP= # 필수: Azure 리소스 그룹 이름
AZURE_APPINSIGHTS_NAME= # 필수: Application Insights 구성 요소 이름
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필수
인증
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;
// 로컬 개발 환경: DefaultAzureCredential. 프로덕션 환경: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=설정
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 또는 프로덕션 환경에서 특정 자격 증명을 직접 사용:
// https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes 참조
// var credential = new ManagedIdentityCredential();
ArmClient client = new ArmClient(credential);
리소스 계층 구조
구독
└── 리소스 그룹
└── ApplicationInsightsComponent # App Insights 리소스
├── ApplicationInsightsComponentApiKey # 프로그래밍 방식 액세스를 위한 API 키
├── ComponentLinkedStorageAccount # 데이터 내보내기를 위한 연결된 스토리지
└── (컴포넌트 ID를 통해)
├── WebTest # 가용성 테스트
├── Workbook # 분석용 워크북
├── WorkbookTemplate # 워크북 템플릿
└── MyWorkbook # 비공개 워크북
핵심 워크플로
1. Application Insights 구성 요소 생성(워크스페이스 기반)
using Azure.ResourceManager.ApplicationInsights;
using Azure.ResourceManager.ApplicationInsights.Models;
ResourceGroupResource resourceGroup = await client
.GetDefaultSubscriptionAsync()
.Result
.GetResourceGroupAsync("my-resource-group");
ApplicationInsightsComponentCollection components = resourceGroup.GetApplicationInsightsComponents();
// 워크스페이스 기반 Application Insights (권장)
ApplicationInsightsComponentData data = new ApplicationInsightsComponentData(
AzureLocation.EastUS,
ApplicationInsightsApplicationType.Web)
{
Kind = "web",
WorkspaceResourceId = new ResourceIdentifier(
"/subscriptions//resourceGroups//providers/Microsoft.OperationalInsights/workspaces/"),
IngestionMode = IngestionMode.LogAnalytics,
PublicNetworkAccessForIngestion = PublicNetworkAccessType.Enabled,
PublicNetworkAccessForQuery = PublicNetworkAccessType.Enabled,
RetentionInDays = 90,
SamplingPercentage = 100,
DisableIPMasking = false,
ImmediatePurgeDataOn30Days = false,
Tags =
{
{ "environment", "production" },
{ "application", "mywebapp" }
}
};
ArmOperation operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
ApplicationInsightsComponentResource component = operation.Value;
Console.WriteLine($"컴포넌트 생성됨: {component.Data.Name}");
Console.WriteLine($"계측 키: {component.Data.InstrumentationKey}");
Console.WriteLine($"연결 문자열: {component.Data.ConnectionString}");
2. 연결 문자열 및 키 가져오기
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// SDK 구성을 위한 연결 문자열 가져오기
string connectionString = component.Data.ConnectionString;
string instrumentationKey = component.Data.InstrumentationKey;
string appId = component.Data.AppId;
Console.WriteLine($"연결 문자열: {connectionString}");
Console.WriteLine($"계측 키: {instrumentationKey}");
Console.WriteLine($"앱 ID: {appId}");
3. API 키 생성
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ApplicationInsightsComponentApiKeyCollection apiKeys = component.GetApplicationInsightsComponentApiKeys();
// 텔레메트리 읽기용 API 키
ApplicationInsightsApiKeyContent keyContent = new ApplicationInsightsApiKeyContent
{
Name = "ReadTelemetryKey",
LinkedReadProperties =
{
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/api",
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/api",
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/agentconfig"
}
};
ApplicationInsightsComponentApiKeyResource apiKey = await apiKeys
.CreateOrUpdateAsync(WaitUntil.Completed, keyContent);
Console.WriteLine($"API 키 이름: {apiKey.Data.Name}");
Console.WriteLine($"API 키: {apiKey.Data.ApiKey}"); // 한 번만 표시됨!
4. 웹 테스트 생성 (가용성 테스트)
WebTestCollection webTests = resourceGroup.GetWebTests();
// URL 핑 테스트
WebTestData urlPingTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.Ping,
SyntheticMonitorId = "webtest-ping-myapp",
WebTestName = "홈페이지 가용성",
Description = "홈페이지 접속 가능 여부 확인",
IsEnabled = true,
Frequency = 300, // 5분
Timeout = 120, // 2분
WebTestKind = WebTestKind.Ping,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }, // 미국 서부
new WebTestGeolocation { WebTestLocationId = "us-tx-sn1-azr" }, // 미국 중남부
new WebTestGeolocation { WebTestLocationId = "us-il-ch1-azr" }, // 미국 중북부
new WebTestGeolocation { WebTestLocationId = "emea-gb-db3-azr" }, // 영국 남부
new WebTestGeolocation { WebTestLocationId = "apac-sg-sin-azr" } // 동남아시아
},
Configuration = new WebTestConfiguration
{
WebTest = """
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
ArmOperation operation = await webTests
.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-homepage", urlPingTest);
WebTestResource webTest = operation.Value;
Console.WriteLine($"웹 테스트 생성됨: {webTest.Data.Name}");
5. 다단계 웹 테스트 생성
WebTestData multiStepTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.MultiStep,
SyntheticMonitorId = "webtest-multistep-login",
WebTestName = "로그인 흐름 테스트",
Description = "로그인 기능 테스트",
IsEnabled = true,
Frequency = 900, // 15분
Timeout = 300, // 5분
WebTestKind = WebTestKind.MultiStep,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }
},
Configuration = new WebTestConfiguration
{
WebTest = """
{"username":"testuser","password":"{{TestPassword}}"}
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
await webTests.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-login-flow", multiStepTest);
6. 워크북 생성
WorkbookCollection workbooks = resourceGroup.GetWorkbooks();
WorkbookData workbookData = new WorkbookData(AzureLocation.EastUS)
{
DisplayName = "애플리케이션 성능 대시보드",
Category = "workbook",
Kind = WorkbookSharedTypeKind.Shared,
SerializedData = """
{
"version": "Notebook/1.0",
"items": [
{
"type": 1,
"content": {
"json": "# 애플리케이션 성능\n\n이 워크북은 애플리케이션 성능 메트릭을 보여줍니다."
},
"name": "header"
},
{
"type": 3,
"content": {
"version": "KqlItem/1.0",
"query": "requests\n| summarize count() by bin(timestamp, 1h)\n| render timechart",
"size": 0,
"title": "시간당 요청 수",
"timeContext": {
"durationMs": 86400000
},
"queryType": 0,
"resourceType": "microsoft.insights/components"
},
"name": "requestsChart"
}
],
"isLocked": false
}
""",
SourceId = component.Id,
Tags =
{
{ "environment", "production" }
}
};
// 참고: 워크북 ID는 새로운 GUID여야 합니다.
string workbookId = Guid.NewGuid().ToString();
ArmOperation operation = await workbooks
.CreateOrUpdateAsync(WaitUntil.Completed, workbookId, workbookData);
WorkbookResource workbook = operation.Value;
Console.WriteLine($"워크북 생성됨: {workbook.Data.DisplayName}");
7. 스토리지 계정 연결
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ComponentLinkedStorageAccountCollection linkedStorage = component.GetComponentLinkedStorageAccounts();
ComponentLinkedStorageAccountData storageData = new ComponentLinkedStorageAccountData
{
LinkedStorageAccount = new ResourceIdentifier(
"/subscriptions//resourceGroups//providers/Microsoft.Storage/storageAccounts/")
};
ArmOperation operation = await linkedStorage
.CreateOrUpdateAsync(WaitUntil.Completed, StorageType.ServiceProfiler, storageData);
8. 구성 요소 나열 및 관리
// 리소스 그룹 내의 모든 Application Insights 구성 요소 나열
await foreach (ApplicationInsightsComponentResource component in
resourceGroup.GetApplicationInsightsComponents())
{
Console.WriteLine($"구성 요소: {component.Data.Name}");
Console.WriteLine($" 앱 ID: {component.Data.AppId}");
Console.WriteLine($" 유형: {component.Data.ApplicationType}");
Console.WriteLine($" 데이터 수집 모드: {component.Data.IngestionMode}");
Console.WriteLine($" 보존 기간: {component.Data.RetentionInDays} 일");
}
// 웹 테스트 나열
await foreach (WebTestResource webTest in resourceGroup.GetWebTests())
{
Console.WriteLine($"웹 테스트: {webTest.Data.WebTestName}");
Console.WriteLine($" 활성화 상태: {webTest.Data.IsEnabled}");
Console.WriteLine($" 실행 빈도: {webTest.Data.Frequency}초");
}
// 워크북 나열
await foreach (WorkbookResource workbook in resourceGroup.GetWorkbooks())
{
Console.WriteLine($"워크북: {workbook.Data.DisplayName}");
}
9. 컴포넌트 업데이트
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// 전체 데이터를 사용하여 업데이트 (PUT 작업)
ApplicationInsightsComponentData updateData = component.Data;
updateData.RetentionInDays = 180;
updateData.SamplingPercentage = 50;
updateData.Tags["updated"] = "true";
ArmOperation operation = await resourceGroup
.GetApplicationInsightsComponents()
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", updateData);
10. 리소스 삭제
// Application Insights 구성 요소 삭제
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
await component.DeleteAsync(WaitUntil.Completed);
// 웹 테스트 삭제
WebTestResource webTest = await resourceGroup.GetWebTestAsync("webtest-homepage");
await webTest.DeleteAsync(WaitUntil.Completed);
키 유형 참조
| 유형 | 용도 |
|---|---|
ApplicationInsightsComponentResource |
App Insights 구성 요소 |
ApplicationInsightsComponentData |
컴포넌트 구성 |
ApplicationInsightsComponentCollection |
컴포넌트 모음 |
ApplicationInsightsComponentApiKeyResource |
프로그래밍 방식 액세스를 위한 API 키 |
WebTestResource |
가용성/웹 테스트 |
WebTestData |
웹 테스트 구성 |
워크북 리소스 |
분석 워크북 |
워크북 데이터 |
워크북 구성 |
ComponentLinkedStorageAccountResource |
내보내기를 위한 연결된 스토리지 |
애플리케이션 유형
| 유형 | 열거형 값 |
|---|---|
| 웹 애플리케이션 | 웹 |
| iOS 애플리케이션 | iOS |
| Java 애플리케이션 | Java |
| Node.js 애플리케이션 | Node.js |
| .NET 애플리케이션 | MRT |
| 기타 | 기타 |
웹 테스트 위치
| 위치 ID | 지역 |
|---|---|
us-ca-sjc-azr |
미국 서부 |
us-tx-sn1-azr |
미국 중남부 |
us-il-ch1-azr |
미국 중북부 |
us-va-ash-azr |
미국 동부 |
emea-gb-db3-azr |
영국 남부 |
emea-nl-ams-azr |
서유럽 |
emea-fr-pra-edge |
프랑스 중부 |
apac-sg-sin-azr |
동남아시아 |
apac-hk-hkn-azr |
동아시아 |
apac-jp-kaw-edge |
일본 동부 |
latam-br-gru-edge |
브라질 남부 |
emea-au-syd-edge |
호주 동부 |
모범 사례
- 워크스페이스 기반 사용 — 워크스페이스 기반 App Insights가 현재 표준입니다
- Log Analytics 연동 — 더 나은 쿼리 수행을 위해 Log Analytics에 데이터를 저장하세요
- 적절한 보존 기간 설정 — 비용과 데이터 가용성 간의 균형 유지
- 샘플링 사용 — 데이터 양이 많은 애플리케이션의 비용 절감
- 연결 문자열을 안전하게 저장 — Key Vault 또는 관리형 ID 사용
- 여러 테스트 위치 활성화 — 정확한 가용성 모니터링을 위해
- 워크북 사용 — 사용자 지정 대시보드 및 분석용
- 알림 설정 — 가용성 테스트 및 지표 기반
- 리소스에 태그 지정 — 비용 배분 및 체계적인 관리를 위해
- 비공개 엔드포인트 사용 — 안전한 데이터 수집을 위해
오류 처리
Azure 사용;
try
{
ArmOperation operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
Console.WriteLine("컴포넌트가 이미 존재합니다");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
Console.WriteLine($"잘못된 구성: {ex.Message}");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Azure 오류: {ex.Status} - {ex.Message}");
}
SDK 통합
Application Insights SDK에서 연결 문자열을 사용하세요:
// ASP.NET Core의 Program.cs
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.ConnectionString = configuration["ApplicationInsights:ConnectionString"];
});
// 또는 환경 변수를 통해 설정
// APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...
관련 SDK
| SDK | 용도 | 설치 |
|---|---|---|
Azure.ResourceManager.ApplicationInsights |
리소스 관리(이 SDK) | dotnet add package Azure.ResourceManager.ApplicationInsights |
Microsoft.ApplicationInsights |
텔레메트리 SDK | dotnet add package Microsoft.ApplicationInsights |
Microsoft.ApplicationInsights.AspNetCore |
ASP.NET Core 통합 | dotnet add package Microsoft.ApplicationInsights.AspNetCore |
Azure.Monitor.OpenTelemetry.Exporter |
OpenTelemetry 내보내기 | dotnet add package Azure.Monitor.OpenTelemetry.Exporter |
참고 링크
| 리소스 | URL |
|---|---|
| NuGet 패키지 | https://www.nuget.org/packages/Azure.ResourceManager.ApplicationInsights |
| API 참조 | https://learn.microsoft.com/dotnet/api/azure.resourcemanager.applicationinsights |
| 제품 설명서 | https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview |
| GitHub 소스 | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/applicationinsights/Azure.ResourceManager.ApplicationInsights |
---
name: azure-mgmt-applicationinsights-dotnet
description: Manage Azure Application Insights resources including components, web tests, workbooks, and API keys using the .NET SDK.
license: MIT
---
# Azure.ResourceManager.ApplicationInsights (.NET)
Azure Resource Manager SDK for managing Application Insights resources for application performance monitoring.
## Installation
```bash
dotnet add package Azure.ResourceManager.ApplicationInsights
dotnet add package Azure.Identity
```
**Current Version**: v1.0.0 (GA)
**API Version**: 2022-06-15
## Environment Variables
```bash
AZURE_SUBSCRIPTION_ID=<your-subscription-id> # Required: Azure subscription ID
AZURE_RESOURCE_GROUP=<your-resource-group> # Required: Azure resource group name
AZURE_APPINSIGHTS_NAME=<your-appinsights-component> # Required: Application Insights component name
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication
```csharp
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
ArmClient client = new ArmClient(credential);
```
## Resource Hierarchy
```
Subscription
└── ResourceGroup
└── ApplicationInsightsComponent # App Insights resource
├── ApplicationInsightsComponentApiKey # API keys for programmatic access
├── ComponentLinkedStorageAccount # Linked storage for data export
└── (via component ID)
├── WebTest # Availability tests
├── Workbook # Workbooks for analysis
├── WorkbookTemplate # Workbook templates
└── MyWorkbook # Private workbooks
```
## Core Workflows
### 1. Create Application Insights Component (Workspace-based)
```csharp
using Azure.ResourceManager.ApplicationInsights;
using Azure.ResourceManager.ApplicationInsights.Models;
ResourceGroupResource resourceGroup = await client
.GetDefaultSubscriptionAsync()
.Result
.GetResourceGroupAsync("my-resource-group");
ApplicationInsightsComponentCollection components = resourceGroup.GetApplicationInsightsComponents();
// Workspace-based Application Insights (recommended)
ApplicationInsightsComponentData data = new ApplicationInsightsComponentData(
AzureLocation.EastUS,
ApplicationInsightsApplicationType.Web)
{
Kind = "web",
WorkspaceResourceId = new ResourceIdentifier(
"/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.OperationalInsights/workspaces/<workspace-name>"),
IngestionMode = IngestionMode.LogAnalytics,
PublicNetworkAccessForIngestion = PublicNetworkAccessType.Enabled,
PublicNetworkAccessForQuery = PublicNetworkAccessType.Enabled,
RetentionInDays = 90,
SamplingPercentage = 100,
DisableIPMasking = false,
ImmediatePurgeDataOn30Days = false,
Tags =
{
{ "environment", "production" },
{ "application", "mywebapp" }
}
};
ArmOperation<ApplicationInsightsComponentResource> operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
ApplicationInsightsComponentResource component = operation.Value;
Console.WriteLine($"Component created: {component.Data.Name}");
Console.WriteLine($"Instrumentation Key: {component.Data.InstrumentationKey}");
Console.WriteLine($"Connection String: {component.Data.ConnectionString}");
```
### 2. Get Connection String and Keys
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// Get connection string for SDK configuration
string connectionString = component.Data.ConnectionString;
string instrumentationKey = component.Data.InstrumentationKey;
string appId = component.Data.AppId;
Console.WriteLine($"Connection String: {connectionString}");
Console.WriteLine($"Instrumentation Key: {instrumentationKey}");
Console.WriteLine($"App ID: {appId}");
```
### 3. Create API Key
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ApplicationInsightsComponentApiKeyCollection apiKeys = component.GetApplicationInsightsComponentApiKeys();
// API key for reading telemetry
ApplicationInsightsApiKeyContent keyContent = new ApplicationInsightsApiKeyContent
{
Name = "ReadTelemetryKey",
LinkedReadProperties =
{
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/api",
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/agentconfig"
}
};
ApplicationInsightsComponentApiKeyResource apiKey = await apiKeys
.CreateOrUpdateAsync(WaitUntil.Completed, keyContent);
Console.WriteLine($"API Key Name: {apiKey.Data.Name}");
Console.WriteLine($"API Key: {apiKey.Data.ApiKey}"); // Only shown once!
```
### 4. Create Web Test (Availability Test)
```csharp
WebTestCollection webTests = resourceGroup.GetWebTests();
// URL Ping Test
WebTestData urlPingTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.Ping,
SyntheticMonitorId = "webtest-ping-myapp",
WebTestName = "Homepage Availability",
Description = "Checks if homepage is available",
IsEnabled = true,
Frequency = 300, // 5 minutes
Timeout = 120, // 2 minutes
WebTestKind = WebTestKind.Ping,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }, // West US
new WebTestGeolocation { WebTestLocationId = "us-tx-sn1-azr" }, // South Central US
new WebTestGeolocation { WebTestLocationId = "us-il-ch1-azr" }, // North Central US
new WebTestGeolocation { WebTestLocationId = "emea-gb-db3-azr" }, // UK South
new WebTestGeolocation { WebTestLocationId = "apac-sg-sin-azr" } // Southeast Asia
},
Configuration = new WebTestConfiguration
{
WebTest = """
<WebTest Name="Homepage" Enabled="True" Timeout="120"
xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Items>
<Request Method="GET" Version="1.1" Url="https://myapp.example.com"
ThinkTime="0" Timeout="120" ParseDependentRequests="False"
FollowRedirects="True" RecordResult="True" Cache="False"
ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="200" />
</Items>
</WebTest>
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
ArmOperation<WebTestResource> operation = await webTests
.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-homepage", urlPingTest);
WebTestResource webTest = operation.Value;
Console.WriteLine($"Web test created: {webTest.Data.Name}");
```
### 5. Create Multi-Step Web Test
```csharp
WebTestData multiStepTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.MultiStep,
SyntheticMonitorId = "webtest-multistep-login",
WebTestName = "Login Flow Test",
Description = "Tests login functionality",
IsEnabled = true,
Frequency = 900, // 15 minutes
Timeout = 300, // 5 minutes
WebTestKind = WebTestKind.MultiStep,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }
},
Configuration = new WebTestConfiguration
{
WebTest = """
<WebTest Name="LoginFlow" Enabled="True" Timeout="300"
xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Items>
<Request Method="GET" Version="1.1" Url="https://myapp.example.com/login"
ThinkTime="0" Timeout="60" />
<Request Method="POST" Version="1.1" Url="https://myapp.example.com/api/auth"
ThinkTime="0" Timeout="60">
<Headers>
<Header Name="Content-Type" Value="application/json" />
</Headers>
<Body>{"username":"testuser","password":"{{TestPassword}}"}</Body>
</Request>
</Items>
</WebTest>
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
await webTests.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-login-flow", multiStepTest);
```
### 6. Create Workbook
```csharp
WorkbookCollection workbooks = resourceGroup.GetWorkbooks();
WorkbookData workbookData = new WorkbookData(AzureLocation.EastUS)
{
DisplayName = "Application Performance Dashboard",
Category = "workbook",
Kind = WorkbookSharedTypeKind.Shared,
SerializedData = """
{
"version": "Notebook/1.0",
"items": [
{
"type": 1,
"content": {
"json": "# Application Performance\n\nThis workbook shows application performance metrics."
},
"name": "header"
},
{
"type": 3,
"content": {
"version": "KqlItem/1.0",
"query": "requests\n| summarize count() by bin(timestamp, 1h)\n| render timechart",
"size": 0,
"title": "Requests per Hour",
"timeContext": {
"durationMs": 86400000
},
"queryType": 0,
"resourceType": "microsoft.insights/components"
},
"name": "requestsChart"
}
],
"isLocked": false
}
""",
SourceId = component.Id,
Tags =
{
{ "environment", "production" }
}
};
// Note: Workbook ID should be a new GUID
string workbookId = Guid.NewGuid().ToString();
ArmOperation<WorkbookResource> operation = await workbooks
.CreateOrUpdateAsync(WaitUntil.Completed, workbookId, workbookData);
WorkbookResource workbook = operation.Value;
Console.WriteLine($"Workbook created: {workbook.Data.DisplayName}");
```
### 7. Link Storage Account
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ComponentLinkedStorageAccountCollection linkedStorage = component.GetComponentLinkedStorageAccounts();
ComponentLinkedStorageAccountData storageData = new ComponentLinkedStorageAccountData
{
LinkedStorageAccount = new ResourceIdentifier(
"/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<storage-account>")
};
ArmOperation<ComponentLinkedStorageAccountResource> operation = await linkedStorage
.CreateOrUpdateAsync(WaitUntil.Completed, StorageType.ServiceProfiler, storageData);
```
### 8. List and Manage Components
```csharp
// List all Application Insights components in resource group
await foreach (ApplicationInsightsComponentResource component in
resourceGroup.GetApplicationInsightsComponents())
{
Console.WriteLine($"Component: {component.Data.Name}");
Console.WriteLine($" App ID: {component.Data.AppId}");
Console.WriteLine($" Type: {component.Data.ApplicationType}");
Console.WriteLine($" Ingestion Mode: {component.Data.IngestionMode}");
Console.WriteLine($" Retention: {component.Data.RetentionInDays} days");
}
// List web tests
await foreach (WebTestResource webTest in resourceGroup.GetWebTests())
{
Console.WriteLine($"Web Test: {webTest.Data.WebTestName}");
Console.WriteLine($" Enabled: {webTest.Data.IsEnabled}");
Console.WriteLine($" Frequency: {webTest.Data.Frequency}s");
}
// List workbooks
await foreach (WorkbookResource workbook in resourceGroup.GetWorkbooks())
{
Console.WriteLine($"Workbook: {workbook.Data.DisplayName}");
}
```
### 9. Update Component
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// Update using full data (PUT operation)
ApplicationInsightsComponentData updateData = component.Data;
updateData.RetentionInDays = 180;
updateData.SamplingPercentage = 50;
updateData.Tags["updated"] = "true";
ArmOperation<ApplicationInsightsComponentResource> operation = await resourceGroup
.GetApplicationInsightsComponents()
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", updateData);
```
### 10. Delete Resources
```csharp
// Delete Application Insights component
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
await component.DeleteAsync(WaitUntil.Completed);
// Delete web test
WebTestResource webTest = await resourceGroup.GetWebTestAsync("webtest-homepage");
await webTest.DeleteAsync(WaitUntil.Completed);
```
## Key Types Reference
| Type | Purpose |
|------|---------|
| `ApplicationInsightsComponentResource` | App Insights component |
| `ApplicationInsightsComponentData` | Component configuration |
| `ApplicationInsightsComponentCollection` | Collection of components |
| `ApplicationInsightsComponentApiKeyResource` | API key for programmatic access |
| `WebTestResource` | Availability/web test |
| `WebTestData` | Web test configuration |
| `WorkbookResource` | Analysis workbook |
| `WorkbookData` | Workbook configuration |
| `ComponentLinkedStorageAccountResource` | Linked storage for exports |
## Application Types
| Type | Enum Value |
|------|------------|
| Web Application | `Web` |
| iOS Application | `iOS` |
| Java Application | `Java` |
| Node.js Application | `NodeJS` |
| .NET Application | `MRT` |
| Other | `Other` |
## Web Test Locations
| Location ID | Region |
|-------------|--------|
| `us-ca-sjc-azr` | West US |
| `us-tx-sn1-azr` | South Central US |
| `us-il-ch1-azr` | North Central US |
| `us-va-ash-azr` | East US |
| `emea-gb-db3-azr` | UK South |
| `emea-nl-ams-azr` | West Europe |
| `emea-fr-pra-edge` | France Central |
| `apac-sg-sin-azr` | Southeast Asia |
| `apac-hk-hkn-azr` | East Asia |
| `apac-jp-kaw-edge` | Japan East |
| `latam-br-gru-edge` | Brazil South |
| `emea-au-syd-edge` | Australia East |
## Best Practices
1. **Use workspace-based** — Workspace-based App Insights is the current standard
2. **Link to Log Analytics** — Store data in Log Analytics for better querying
3. **Set appropriate retention** — Balance cost vs. data availability
4. **Use sampling** — Reduce costs for high-volume applications
5. **Store connection string securely** — Use Key Vault or managed identity
6. **Enable multiple test locations** — For accurate availability monitoring
7. **Use workbooks** — For custom dashboards and analysis
8. **Set up alerts** — Based on availability tests and metrics
9. **Tag resources** — For cost allocation and organization
10. **Use private endpoints** — For secure data ingestion
## Error Handling
```csharp
using Azure;
try
{
ArmOperation<ApplicationInsightsComponentResource> operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
Console.WriteLine("Component already exists");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
Console.WriteLine($"Invalid configuration: {ex.Message}");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Azure error: {ex.Status} - {ex.Message}");
}
```
## SDK Integration
Use the connection string with Application Insights SDK:
```csharp
// Program.cs in ASP.NET Core
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.ConnectionString = configuration["ApplicationInsights:ConnectionString"];
});
// Or set via environment variable
// APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...
```
## Related SDKs
| SDK | Purpose | Install |
|-----|---------|---------|
| `Azure.ResourceManager.ApplicationInsights` | Resource management (this SDK) | `dotnet add package Azure.ResourceManager.ApplicationInsights` |
| `Microsoft.ApplicationInsights` | Telemetry SDK | `dotnet add package Microsoft.ApplicationInsights` |
| `Microsoft.ApplicationInsights.AspNetCore` | ASP.NET Core integration | `dotnet add package Microsoft.ApplicationInsights.AspNetCore` |
| `Azure.Monitor.OpenTelemetry.Exporter` | OpenTelemetry export | `dotnet add package Azure.Monitor.OpenTelemetry.Exporter` |
## Reference Links
| Resource | URL |
|----------|-----|
| NuGet Package | https://www.nuget.org/packages/Azure.ResourceManager.ApplicationInsights |
| API Reference | https://learn.microsoft.com/dotnet/api/azure.resourcemanager.applicationinsights |
| Product Documentation | https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/applicationinsights/Azure.ResourceManager.ApplicationInsights |
모든 파일
0개 파일azure-mgmt-applicationinsights-dotnet 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-mgmt-applicationinsights-dotnet # Copy SKILL.md to your .claude/skills/ directory
복사





집
