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

为何Application Insights捕获所有Trace日志?已设appsettings.json级别为Information

解决ASP.NET API中Application Insights捕获所有Trace日志的级别过滤问题

问题原因

你使用的ApplicationInsightsTraceListener属于System.Diagnostics.Trace日志体系,而appsettings.json中的Logging配置是针对ASP.NET Core官方的ILogger体系的,两者互不兼容,因此配置的日志级别不会对TraceListener生效,导致所有Trace日志都被捕获。

解决方案

方案一:改用ASP.NET Core官方ILogger体系(推荐)

这是ASP.NET Core的标准日志方案,与Application Insights集成更完善:

  1. 移除代码中Trace.Listeners.Add(...)的相关代码。
  2. 调整appsettings.json的Application Insights日志级别配置,将Default设为Information:
"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft": "Warning"
  },
  "ApplicationInsights": {
    "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning"
    }
}
  1. 在控制器或服务中通过依赖注入ILogger<T>来记录日志,示例:
private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    _logger.LogInformation("This is an info level log");
    _logger.LogTrace("This verbose log will NOT be sent to Application Insights");
    // ...其他逻辑
}

方案二:保留System.Diagnostics.Trace并配置级别过滤

若必须使用Trace日志,需单独为ApplicationInsightsTraceListener设置过滤规则:

代码方式配置

直接在Program.cs中创建TraceSwitch并关联到Listener:

services.AddApplicationInsightsTelemetry();

// 创建TraceSwitch,设置最低日志级别为Information
var aiTraceSwitch = new TraceSwitch("AITraceFilter", "Filter for Application Insights Trace Listener")
{
    Level = TraceLevel.Info // 可选值:Off/Error/Warning/Info/Verbose
};

// 初始化Listener并绑定过滤规则
var aiListener = new Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener();
aiListener.Filter = new System.Diagnostics.TraceFilter(aiTraceSwitch);
Trace.Listeners.Add(aiListener);

配置文件方式

在项目中添加app.config文件(ASP.NET Core项目需手动创建),添加以下配置:

<configuration>
  <system.diagnostics>
    <switches>
      <!-- 设置级别为Info,对应Information -->
      <add name="AITraceFilter" value="Info" />
    </switches>
    <trace autoflush="true">
      <listeners>
        <add name="ApplicationInsightsTraceListener" 
             type="Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener, Microsoft.ApplicationInsights.TraceListener">
          <filter type="System.Diagnostics.TraceFilter" initializeData="AITraceFilter" />
        </add>
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:12:50