关于 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 或托管标识
- 启用多个测试位置 — 确保可用性监视准确
- 使用工作簿 — 创建自定义仪表板并进行分析
- 设置警报 — 根据可用性测试和指标设置警报
- 标记资源 — 便于成本分配和组织管理
- 使用专用终结点 — 确保数据摄取安全
错误处理
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 |
参考链接
适用场景
当需要执行概述中描述的工作流或操作时,可以使用此技能。
限制
- 仅当任务明确符合上述范围时,才使用此技能。
- 不要将输出视为针对特定环境进行验证、测试或专家审查的替代品。
- 如果缺少必需的输入、权限、安全边界或成功标准,请停止并请求澄清。