如何区分Azure Static Web Apps各环境在Application Insights中的日志?
解决方案:无需手动配置多App Insights实例,按环境筛选日志
核心思路
Azure Static Web Apps(ASWA)自带环境标识变量,可通过代码将环境信息注入App Insights的日志属性中,之后就能用KQL精准筛选生产环境日志,无需为每个预发布环境单独配置App Insights实例。
具体步骤
利用ASWA内置环境变量
ASWA自动为每个环境注入AZURE_STATIC_WEB_APPS_ENVIRONMENT变量:- 生产环境值固定为
Production - 预发布环境值为
preview-<PR编号>-<分支名>格式(比如preview-123-main)
- 生产环境值固定为
在应用代码中添加环境属性到日志
根据你使用的开发语言,在发送日志到App Insights时,将环境变量作为自定义属性传入:- JavaScript/TypeScript示例:
const appInsights = require('applicationinsights'); appInsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY).start(); // 发送追踪日志时添加环境属性 appInsights.defaultClient.trackTrace({ message: '用户登录成功', properties: { environment: process.env.AZURE_STATIC_WEB_APPS_ENVIRONMENT } }); - .NET示例:
在Program.cs中添加Telemetry初始化器,自动为所有日志附加环境属性:builder.Services.AddApplicationInsightsTelemetry(); builder.Services.AddSingleton<ITelemetryInitializer>(serviceProvider => { var env = serviceProvider.GetRequiredService<IWebHostEnvironment>(); return new TelemetryInitializer(env.EnvironmentName); }); // 自定义初始化器类 public class TelemetryInitializer : ITelemetryInitializer { private readonly string _environment; public TelemetryInitializer(string environment) => _environment = environment; public void Initialize(ITelemetry telemetry) { telemetry.Context.Properties["environment"] = _environment; } }
- JavaScript/TypeScript示例:
用KQL筛选生产环境日志
日志写入App Insights后,即可通过customDimensions.environment字段筛选:- 筛选生产环境追踪日志:
traces | where customDimensions.environment == "Production" | order by timestamp desc | project timestamp, message, customDimensions - 筛选生产环境异常日志:
exceptions | where customDimensions.environment == "Production" | order by timestamp desc | project timestamp, exceptionType, message, customDimensions
- 筛选生产环境追踪日志:
优势对比
相比为每个预发布环境手动修改APPINSIGHTS_INSTRUMENTATIONKEY的方案,此方法:
- 无需重复配置App Insights实例,节省资源和操作成本
- 所有环境日志统一存储,方便跨环境对比排查问题
- 环境标识自动注入,无需手动维护每个预发布环境的配置
内容的提问来源于stack exchange,提问作者Thomas Jäckle
相关产品推荐
相关产品推荐

