如何禁用.NET 6独立模式Azure Function的Application Insights自动请求日志
解决.NET 6孤立模式Azure Function中Application Insights重复请求日志问题
问题根源
.NET 6孤立模式(Isolated Worker)的Azure Function里,默认Application Insights集成会自动收集请求遥测,加上你自定义TelemetryClient发送的请求日志,就导致请求表出现两条记录。你之前加的EnableRequestTrackingTelemetryModule是in-process模式的配置,对孤立模式完全不生效。
解决步骤
1. 修正host.json配置
在host.json里添加孤立模式专属的禁用自动请求跟踪设置:
{ "version": "2.0", "logging": { "applicationInsights": { "enableRequestTracking": false, "enableDependencyTracking": true // 要是还需要依赖跟踪就保留,不需要就改成false } } }
这个配置会直接关掉Function Worker自动生成的请求遥测,只留你自定义TelemetryClient发的日志。
2. 正确注册自定义TelemetryClient(适配Autofac)
在Autofac模块里注册TelemetryClient时,别自己手动实例化,要从DI容器拿已配置好的实例,保证和Function的操作上下文关联:
// 你的Autofac Module示例 public class Module1 : Module { private readonly IConfiguration _configuration; public Module1(IConfiguration configuration) { _configuration = configuration; } protected override void Load(ContainerBuilder builder) { builder.Register(ctx => { var telemetryConfig = ctx.Resolve<TelemetryConfiguration>(); return new TelemetryClient(telemetryConfig); }).SingleInstance(); } }
3. 备选:用代码配置禁用自动请求跟踪
如果host.json配置没效果,就在Program.cs的ConfigureServices里手动配置Application Insights,关闭请求跟踪:
.ConfigureServices((context, services) => { services.AddApplicationInsightsTelemetryWorkerService(options => { options.EnableRequestTracking = false; }); // 其他服务配置代码... })
验证
改完配置重新部署Function,触发调用后去Application Insights的请求表里看,应该只会显示一条自定义TelemetryClient生成的请求日志。
内容的提问来源于stack exchange,提问作者Suyog Arun Khachane
相关产品推荐
相关产品推荐

