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

如何在Azure Function中按函数级别实现Application Insights采样

.NET Core 6 Azure Function 按函数自定义Application Insights日志采样方案

要实现仅对Function2日志采样、保留Function1和Function3全量日志的需求,你可以通过自定义遥测处理器精准控制采样逻辑,具体步骤如下:

1. 实现自定义采样处理器

创建继承ITelemetryProcessor的类,在Process方法中根据函数名判断是否执行采样:

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;

public class FunctionSpecificSamplingProcessor : ITelemetryProcessor
{
    private readonly ITelemetryProcessor _next;
    // 可自定义Function2的采样率,比如保留10%日志
    private const double Function2SamplingRate = 0.1;
    private static readonly Random _random = new();

    public FunctionSpecificSamplingProcessor(ITelemetryProcessor next)
    {
        _next = next;
    }

    public void Process(ITelemetry telemetry)
    {
        // 从遥测中提取当前函数名,Azure Function默认格式为"Function.FunctionName"
        var functionName = telemetry.Context.Operation.Name?.Split('.').LastOrDefault();

        if (string.Equals(functionName, "Function2", StringComparison.OrdinalIgnoreCase))
        {
            // 执行采样:随机数小于采样率则保留日志,否则直接跳过
            if (_random.NextDouble() > Function2SamplingRate)
            {
                return;
            }
        }

        // 非Function2日志或采样命中的日志,继续传递到后续处理器
        _next.Process(telemetry);
    }
}

2. 注册自定义处理器到依赖注入

在Program.cs中,将自定义处理器加入Application Insights遥测管道:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        // 注册自定义采样处理器
        services.AddTelemetryProcessor<FunctionSpecificSamplingProcessor>();
    })
    .Build();

host.Run();

3. 细节调整说明

  • 函数名匹配:如果你的函数遥测Operation.Name格式特殊(比如带触发器后缀),可以改用Contains("Function2")来模糊匹配。
  • 采样率灵活调整:修改Function2SamplingRate的值即可调整比例,1.0代表全量保留,0代表完全丢弃。
  • 定向采样:如果仅需对Trace日志采样,可在Process方法开头增加判断:if (telemetry is not TraceTelemetry) { _next.Process(telemetry); return; }。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:23:24