mcpField
A
azure-mgmt-applicationinsights-dotnet

azure-mgmt-applicationinsights-dotnet

github.com/sickn33クラウド・DevOps48.7k54 回インストール今日更新
リポジトリ

azure-mgmt-applicationinsights-dotnet について

.NET 開発者向けの Azure Application Insights リソース管理 SDK ガイドです。Azure Resource Manager を使い、監視コンポーネント、ブック、リンクされたストレージなどを管理します。

主な機能

  1. 01コンポーネントの作成・参照・更新
  2. 02ブックとリンクストレージの管理
  3. 03可用性テストの設定
  4. 04リソースの一覧表示と削除

活用シーン

  1. 01アプリ用 Application Insights コンポーネントの作成
  2. 02コンポーネントのサンプリングと保持設定の更新
  3. 03分析用ブックの設定
  4. 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);

主要な型のリファレンス

型用途
ApplicationInsightsComponentResourceApp Insights コンポーネント
ApplicationInsightsComponentDataコンポーネントの構成
ApplicationInsightsComponentCollectionコンポーネントのコレクション
ApplicationInsightsComponentApiKeyResourceプログラムによるアクセス用 API キー
WebTestResource可用性/Web テスト
WebTestDataWeb テストの構成
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オーストラリア東部

ベストプラクティス

  1. ワークスペースベースを使用する — ワークスペースベースの App Insights が現在の標準です
  2. Log Analytics にリンクする — クエリを改善するため、データを Log Analytics に保存します
  3. 適切な保持期間を設定する — コストとデータの可用性のバランスを取ります
  4. サンプリングを使用する — 大量のデータを扱うアプリケーションのコストを削減します
  5. 接続文字列を安全に保存する — Key Vault またはマネージド ID を使用します
  6. 複数のテストロケーションを有効にする — 正確な可用性監視のために設定します
  7. ワークブックを使用する — カスタムダッシュボードと分析に使用します
  8. アラートを設定する — 可用性テストとメトリックに基づいて設定します
  9. リソースにタグを付ける — コストの割り当てと整理に役立ちます
  10. プライベートエンドポイントを使用する — 安全にデータを取り込むために使用します

エラー処理

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テレメトリ SDKdotnet add package Microsoft.ApplicationInsights
Microsoft.ApplicationInsights.AspNetCoreASP.NET Core 統合dotnet add package Microsoft.ApplicationInsights.AspNetCore
Azure.Monitor.OpenTelemetry.ExporterOpenTelemetry エクスポート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

使用する場合

このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記の説明範囲に明確に該当する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
  • 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中断して確認を求めてください。

コメント