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

为何Application Insights仅显示Warning及以上级别日志?如何查看全量日志?

解决方案

1. 安装适配的NuGet包

针对.NET Framework 4.5.1,安装以下低版本兼容包(过高版本不支持4.5.1框架),两个包版本需保持一致:

  • Microsoft.ApplicationInsights.Web(推荐2.21.0版本)
  • Microsoft.ApplicationInsights.TraceListener

2. 配置Trace监听器

在web.config的configuration节点下新增如下配置,将Trace输出定向到Application Insights:

<system.diagnostics>
  <trace autoflush="true" indentsize="4">
    <listeners>
      <add name="ApplicationInsightsTraceListener" type="Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener, Microsoft.ApplicationInsights.TraceListener" />
      <remove name="Default" />
    </listeners>
  </trace>
</system.diagnostics>

3. 调整Application Insights日志采集级别

默认Application Insights会过滤Verbose、Information级别的日志,需要修改ApplicationInsights.config文件:

  • 找到配置里的<TelemetryProcessors>节点,删除针对Trace的默认采样过滤节点(如果存在):
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
  <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
  <IncludedTypes>Trace</IncludedTypes>
</Add>

如果需要全量采集,可直接移除所有Trace相关的采样规则;如果需要保留采样,可调整规则包含所有级别日志。

  • 同时在web.config的appSettings节点确认InstrumentationKey配置正确:
<add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="你的Application Insights资源的InstrumentationKey" />

4. 捕获Console.WriteLine输出

如果需要采集Console.WriteLine的内容,在Global.asax的Application_Start方法中添加如下代码,将控制台输出重定向到Trace流:

public class Global : HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        // 新增控制台输出重定向代码
        Console.SetOut(new TraceWriter());
    }
}

// 自定义TraceWriter类
public class TraceWriter : TextWriter
{
    public override Encoding Encoding => Encoding.UTF8;

    public override void WriteLine(string value)
    {
        Trace.WriteLine(value);
    }
}

5. Azure门户配置验证

  • 进入App Service的「Application Insights」配置页,确认「Application Insights集成」状态为开启
  • 进入「App Service日志」页,确认「应用程序日志(Application Insights)」的级别设置为Verbose

6. 日志查询验证

部署应用后进入Application Insights的「日志」查询页,执行如下语句即可查看全量日志:

traces
| order by timestamp desc

其中severityLevel字段对应日志级别:0=Verbose、1=Information、2=Warning、3=Error、4=Critical,无需额外过滤即可看到所有级别的输出。

可在Application Insights的「使用情况和预估成本」->「数据保留」页自行设置日志保留周期,最长支持保留730天,长期归档可配置自动导出到Blob存储。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:24:01