You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Web应用:如何配置Application Insights全量收集Trace日志并保留自适应采样

解决方案:全量收集Trace日志且保留原有自适应采样

无需切换到手动SDK配置,通过现有配置即可实现目标

方法1:修改ApplicationInsights.config,为Trace遥测单独排除采样

在自适应采样处理器的配置中,添加ExcludedTypes属性指定排除Trace类型,让采样逻辑仅作用于其他遥测(如请求、依赖项等):

<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
  <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
  <ExcludedTypes>Trace</ExcludedTypes> <!-- 新增该行,排除Trace日志的采样 -->
</Add>

此配置会让所有Trace日志绕过自适应采样,实现全量收集,同时不影响其他类型遥测的采样规则。

方法2:自定义采样处理器(用于更灵活的控制场景)

如果需要更精细的规则,可在应用启动代码中替换默认采样处理器,仅对非Trace遥测应用采样:

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
using Microsoft.ApplicationInsights.DataContracts;

protected void Application_Start()
{
    var config = TelemetryConfiguration.Active;
    // 移除默认自适应采样处理器
    var defaultSampler = config.TelemetryProcessors.OfType<AdaptiveSamplingTelemetryProcessor>().FirstOrDefault();
    if (defaultSampler != null)
    {
        config.TelemetryProcessors.Remove(defaultSampler);
    }
    // 添加自定义采样处理器
    config.TelemetryProcessors.Add(new TraceExcludedSamplingProcessor());
}

public class TraceExcludedSamplingProcessor : ITelemetryProcessor
{
    private readonly ITelemetryProcessor _nextProcessor;
    private readonly AdaptiveSamplingTelemetryProcessor _samplingProcessor;

    public TraceExcludedSamplingProcessor(ITelemetryProcessor next)
    {
        _nextProcessor = next;
        // 初始化自适应采样器,沿用原有配置参数
        _samplingProcessor = new AdaptiveSamplingTelemetryProcessor(next)
        {
            MaxTelemetryItemsPerSecond = 5
        };
    }

    public void Process(ITelemetry item)
    {
        if (item is TraceTelemetry)
        {
            // Trace日志直接传递,不经过采样
            _nextProcessor.Process(item);
        }
        else
        {
            // 其他遥测应用自适应采样规则
            _samplingProcessor.Process(item);
        }
    }
}

是否需要改用Application Insights SDK?

不需要。自动检测模式下,通过上述配置修改或少量代码扩展,即可实现Trace日志的全量收集,同时保留原有自适应采样对其他遥测的作用。仅当需要实现极复杂的自定义遥测逻辑时,才需要考虑切换到手动SDK配置。

内容的提问来源于stack exchange,提问作者Weanich Sanchol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:52:42