azure-mgmt-applicationinsights-dotnet について
.NET 開発者向けの Azure Application Insights リソース管理 SDK ガイドです。Azure Resource Manager を使い、監視コンポーネント、ブック、リンクされたストレージなどを管理します。
主な機能
- 01コンポーネントの作成・参照・更新
- 02ブックとリンクストレージの管理
- 03可用性テストの設定
- 04リソースの一覧表示と削除
活用シーン
- 01アプリ用 Application Insights コンポーネントの作成
- 02コンポーネントのサンプリングと保持設定の更新
- 03分析用ブックの設定
- 04可用性監視リソースの管理
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-mgmt-applicationinsights-dotnetインストール後、Claude Code で/azure-mgmt-applicationinsights-dotnetを入力して読み込まれたか確認します。
詳細
Azure.ResourceManager.ApplicationInsights(.NET)
アプリケーションのパフォーマンス監視を目的として Application Insights リソースを管理する Azure Resource Manager SDK です。
インストール
dotnet add package Azure.ResourceManager.ApplicationInsights
dotnet add package Azure.Identity
サポート対象でテスト済みの SDK バージョンを固定し、各操作を API リファレンスと照合してください。パッケージのバージョンと ARM API のバージョンは異なります。これらの独立した断片は、単一のコンパイル可能なプログラムではありません。
環境変数
AZURE_SUBSCRIPTION_ID=<your-subscription-id>
AZURE_RESOURCE_GROUP=<your-resource-group>
AZURE_APPINSIGHTS_NAME=<your-appinsights-component>
認証
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;
ArmClient client = new ArmClient(new DefaultAzureCredential());
リソース階層
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
対象のテナント/サブスクリプションを選択し、資格情報とロールを確認してください。作成/更新/削除操作とスケジュールされたテストには、対象固有の認可、コストの確認、ロールバック/保持の計画が必要です。テレメトリの内容やキーをログに記録しないでください。ワークスペースベースの保持期間は、リンクされたワークスペース/テーブルの構成によって決まります。コンポーネントのフィールドだけでは、実際の保持期間やアプリケーション SDK のサンプリングは確定しません。Private Link を使用するには、スコープ、DNS、アクセス ポリシーをすべて設定する必要があります。
主なワークフロー
1. Application Insights コンポーネントを作成する(ワークスペースベース)
using Azure.ResourceManager.ApplicationInsights;
using Azure.ResourceManager.ApplicationInsights.Models;
using Azure;
using Azure.Core;
using Azure.ResourceManager.Resources;
string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID")
?? throw new InvalidOperationException("Missing subscription");
SubscriptionResource subscription = client.GetSubscriptionResource(
new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
ResourceGroupResource resourceGroup = (await subscription
.GetResourceGroupAsync("my-resource-group")).Value;
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}");
// Keep ingestion identifiers in approved configuration; do not log them.
// Pass the connection string to approved configuration without logging.
2. 接続文字列とキーを取得する
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;
// Do not print connectionString.
// Do not print instrumentationKey.
Console.WriteLine($"App ID: {appId}");
3. テレメトリ クエリの認証
サポートされている Microsoft Entra 認証を優先し、最小権限のクエリ ロールを使用してください。従来のテレメトリ クエリ API キーを作成またはログに記録しないでください。既存のクライアントを移行する前に、現在のクエリ API/認証のライフサイクルを確認してください。管理プレーンの資格情報は、データ取り込みやクエリのアクセスとは別です。
4. 可用性の監視
新しいデプロイには、サポートされている Standard 可用性テストを使用してください。以前の URL Ping XML の例は非推奨となり、複数ステップの .webtest テストは2024年に廃止されました。スケジュールされたテストを有効にする前に、現在のリージョン/場所の識別子、料金、リクエスト/レスポンスの検証、再試行ポリシー、TLS 設定を確認してください。複数リクエストからなる一連の処理には、明示的にサポートされている合成テストランナーを選択し、テスト専用の資格情報を使用してください。このスキルでは、そのようなランナーを提供していません。ARM SDK が {{TestPassword}} の補間を提供すると想定しないでください。
6. ブックを作成する
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. ストレージ アカウントをリンクする
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 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. コンポーネントを更新する
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 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);
主要な型のリファレンス
| 型 | 用途 |
|---|---|
ApplicationInsightsComponentResource | App Insights コンポーネント |
ApplicationInsightsComponentData | コンポーネントの構成 |
ApplicationInsightsComponentCollection | コンポーネントのコレクション |
ApplicationInsightsComponentApiKeyResource | プログラムによるアクセス用 API キー |
WebTestResource | 可用性/Web テスト |
WebTestData | Web テストの構成 |
WorkbookResource | 分析ブック |
WorkbookData | ブックの構成 |
ComponentLinkedStorageAccountResource | エクスポート用のリンクされたストレージ |
アプリケーションの種類
| 種類 | 列挙値 |
|---|---|
| Web アプリケーション | Web |
| iOS アプリケーション | iOS |
| Java アプリケーション | Java |
| Node.js アプリケーション | NodeJS |
| .NET アプリケーション | MRT |
| その他 | Other |
Web テストの場所
| 場所 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 を使用します
- 複数のテストロケーションを有効にする — 正確な可用性監視のために設定します
- ワークブックを使用する — カスタムダッシュボードと分析に使用します
- アラートを設定する — 可用性テストとメトリックに基づいて設定します
- リソースにタグを付ける — コストの割り当てと整理に役立ちます
- プライベートエンドポイントを使用する — 安全にデータを取り込むために使用します
エラー処理
using Azure;
try
{
ArmOperation<ApplicationInsightsComponentResource> operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
Console.WriteLine("Conflict: inspect structured error/code and current resource state; do not assume existence is the cause.");
}
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 統合
Application Insights SDK で接続文字列を使用します:
// 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=...
関連 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 |
参考リンク
使用する場合
このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の説明範囲に明確に該当する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中断して確認を求めてください。