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

.NET Core如何少改动代码为Application Insights添加请求头自定义属性

实现方案:无需修改现有ILogger调用,将请求头自定义属性加入Application Insights日志

你可以通过以下两种方式实现需求,均不需要改动现有_logger.LogError这类日志调用代码:

方法一:利用日志作用域(Logger Scope)+ 自定义中间件

这种方式会将请求头属性注入当前请求的日志上下文,所有该请求内的日志都会自动带上这些属性。

  1. 创建请求头日志中间件
public class RequestHeaderLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestHeaderLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, ILogger<RequestHeaderLoggingMiddleware> logger)
    {
        // 提取需要的自定义请求头,示例为"X-Custom-Id"和"X-User-Name",可根据实际调整
        var headerProps = new Dictionary<string, string>();
        if (context.Request.Headers.TryGetValue("X-Custom-Id", out var customId))
        {
            headerProps["X-Custom-Id"] = customId.ToString();
        }
        if (context.Request.Headers.TryGetValue("X-User-Name", out var userName))
        {
            headerProps["X-User-Name"] = userName.ToString();
        }

        // 用作用域包裹请求处理,后续所有日志自动携带这些属性
        using (logger.BeginScope(headerProps))
        {
            await _next(context);
        }
    }
}
  1. 注册中间件
    在Program.cs(.NET 6+)或Startup.cs中,将中间件注册到请求管道,注意放在路由中间件之前:
var app = builder.Build();

// 注册自定义中间件
app.UseMiddleware<RequestHeaderLoggingMiddleware>();

app.UseRouting();
// ...其他中间件配置

方法二:自定义TelemetryInitializer

这种方式会将请求头属性添加到所有Application Insights遥测(包括日志、请求、依赖等)的自定义维度中,覆盖范围更广。

  1. 创建Telemetry初始化器
public class RequestHeaderTelemetryInitializer : ITelemetryInitializer
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public RequestHeaderTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void Initialize(ITelemetry telemetry)
    {
        var httpContext = _httpContextAccessor.HttpContext;
        if (httpContext == null) return;

        // 提取并添加自定义请求头到遥测属性
        if (httpContext.Request.Headers.TryGetValue("X-Custom-Id", out var customId))
        {
            telemetry.Properties["X-Custom-Id"] = customId.ToString();
        }
        if (httpContext.Request.Headers.TryGetValue("X-User-Name", out var userName))
        {
            telemetry.Properties["X-User-Name"] = userName.ToString();
        }
    }
}
  1. 注册初始化器
    在Program.cs中添加服务注册:
// 注册HttpContext访问器
builder.Services.AddHttpContextAccessor();
// 注册自定义Telemetry初始化器
builder.Services.AddSingleton<ITelemetryInitializer, RequestHeaderTelemetryInitializer>();

效果说明

两种方式最终都会让你的_logger.LogError日志在Application Insights的Custom Dimensions中显示对应的请求头属性,完全不需要修改现有日志调用代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:32:38