azure-mgmt-applicationinsights-dotnet

npx skills add https://github.com/microsoft/skills --skill azure-mgmt-applicationinsights-dotnet

Azure.ResourceManager.ApplicationInsights (.NET)

SDK Azure Resource Manager pour gérer les ressources Application Insights pour la surveillance des performances applicatives.

Installation

dotnet add package Azure.ResourceManager.ApplicationInsights
dotnet add package Azure.Identity

Version actuelle : v1.0.0 (GA)
Version API : 2022-06-15

Variables d'environnement

AZURE_SUBSCRIPTION_ID=<your-subscription-id>
AZURE_RESOURCE_GROUP=<your-resource-group>
AZURE_APPINSIGHTS_NAME=<your-appinsights-component>

Authentification

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;

ArmClient client = new ArmClient(new DefaultAzureCredential());

Hiérarchie des ressources

Subscription
└── ResourceGroup
    └── ApplicationInsightsComponent          # Ressource App Insights
        ├── ApplicationInsightsComponentApiKey  # Clés API pour accès programmatique
        ├── ComponentLinkedStorageAccount      # Stockage lié pour export de données
        └── (via component ID)
            ├── WebTest                        # Tests de disponibilité
            ├── Workbook                       # Classeurs pour analyse
            ├── WorkbookTemplate               # Modèles de classeurs
            └── MyWorkbook                     # Classeurs privés

Flux de travail essentiels

1. Créer un composant Application Insights (basé sur workspace)

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 basée sur workspace (recommandé)
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. Obtenir la chaîne de connexion et les clés

ApplicationInsightsComponentResource component = await resourceGroup
    .GetApplicationInsightsComponentAsync("my-appinsights");

// Obtenir la chaîne de connexion pour configuration du SDK
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. Créer une clé API

ApplicationInsightsComponentResource component = await resourceGroup
    .GetApplicationInsightsComponentAsync("my-appinsights");

ApplicationInsightsComponentApiKeyCollection apiKeys = component.GetApplicationInsightsComponentApiKeys();

// Clé API pour lire la télémétrie
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}"); // Affiché une seule fois !

4. Créer un test Web (test de disponibilité)

WebTestCollection webTests = resourceGroup.GetWebTests();

// Test de ping URL
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. Créer un test Web multi-étapes

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. Créer un classeur

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: L'ID du classeur doit être un nouveau 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. Lier un compte de stockage

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. Lister et gérer les composants

// Lister tous les composants Application Insights du groupe de ressources
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");
}

// Lister les tests Web
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");
}

// Lister les classeurs
await foreach (WorkbookResource workbook in resourceGroup.GetWorkbooks())
{
    Console.WriteLine($"Workbook: {workbook.Data.DisplayName}");
}

9. Mettre à jour un composant

ApplicationInsightsComponentResource component = await resourceGroup
    .GetApplicationInsightsComponentAsync("my-appinsights");

// Mettre à jour avec données complètes (opération PUT)
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. Supprimer les ressources

// Supprimer le composant Application Insights
ApplicationInsightsComponentResource component = await resourceGroup
    .GetApplicationInsightsComponentAsync("my-appinsights");
await component.DeleteAsync(WaitUntil.Completed);

// Supprimer le test Web
WebTestResource webTest = await resourceGroup.GetWebTestAsync("webtest-homepage");
await webTest.DeleteAsync(WaitUntil.Completed);

Référence des types clés

Type Objectif
ApplicationInsightsComponentResource Composant App Insights
ApplicationInsightsComponentData Configuration du composant
ApplicationInsightsComponentCollection Collection de composants
ApplicationInsightsComponentApiKeyResource Clé API pour accès programmatique
WebTestResource Test de disponibilité/Web
WebTestData Configuration du test Web
WorkbookResource Classeur d'analyse
WorkbookData Configuration du classeur
ComponentLinkedStorageAccountResource Stockage lié pour exports

Types d'applications

Type Valeur d'énumération
Application Web Web
Application iOS iOS
Application Java Java
Application Node.js NodeJS
Application .NET MRT
Autre Other

Emplacements des tests Web

ID d'emplacement Région
us-ca-sjc-azr Ouest des États-Unis
us-tx-sn1-azr Centre-Sud des États-Unis
us-il-ch1-azr Centre-Nord des États-Unis
us-va-ash-azr Est des États-Unis
emea-gb-db3-azr Sud du Royaume-Uni
emea-nl-ams-azr Ouest de l'Europe
emea-fr-pra-edge France Centre
apac-sg-sin-azr Asie du Sud-Est
apac-hk-hkn-azr Asie de l'Est
apac-jp-kaw-edge Japon Est
latam-br-gru-edge Brésil Sud
emea-au-syd-edge Australie Est

Bonnes pratiques

  1. Utiliser basée sur workspace — App Insights basée sur workspace est la norme actuelle
  2. Lier à Log Analytics — Stocker les données dans Log Analytics pour meilleures requêtes
  3. Définir une rétention appropriée — Équilibrer coût vs. disponibilité des données
  4. Utiliser l'échantillonnage — Réduire les coûts pour applications à haut volume
  5. Stocker la chaîne de connexion de manière sécurisée — Utiliser Key Vault ou managed identity
  6. Activer plusieurs emplacements de test — Pour monitoring de disponibilité précis
  7. Utiliser les classeurs — Pour tableaux de bord personnalisés et analyse
  8. Configurer des alertes — Basées sur tests de disponibilité et métriques
  9. Étiqueter les ressources — Pour allocation des coûts et organisation
  10. Utiliser les endpoints privés — Pour ingestion de données sécurisée

Gestion des erreurs

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}");
}

Intégration du SDK

Utiliser la chaîne de connexion avec le SDK Application Insights :

// Program.cs dans ASP.NET Core
builder.Services.AddApplicationInsightsTelemetry(options =>
{
    options.ConnectionString = configuration["ApplicationInsights:ConnectionString"];
});

// Ou définir via variable d'environnement
// APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...

SDKs associés

SDK Objectif Installation
Azure.ResourceManager.ApplicationInsights Gestion des ressources (ce SDK) dotnet add package Azure.ResourceManager.ApplicationInsights
Microsoft.ApplicationInsights SDK de télémétrie dotnet add package Microsoft.ApplicationInsights
Microsoft.ApplicationInsights.AspNetCore Intégration ASP.NET Core dotnet add package Microsoft.ApplicationInsights.AspNetCore
Azure.Monitor.OpenTelemetry.Exporter Export OpenTelemetry dotnet add package Azure.Monitor.OpenTelemetry.Exporter

Liens de référence

Ressource URL
Package NuGet https://www.nuget.org/packages/Azure.ResourceManager.ApplicationInsights
Référence API https://learn.microsoft.com/dotnet/api/azure.resourcemanager.applicationinsights
Documentation du produit https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview
Source GitHub https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/applicationinsights/Azure.ResourceManager.ApplicationInsights

Skills similaires