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

Serilog设置MinimumLevel为Information后无法记录异常至Application Insights

问题描述

我正在开发一个ASP.NET Core MVC应用,希望使用Serilog将跟踪消息(Information)和异常记录至Application Insights。以下是Program.cs中的配置代码:

builder.Host.UseSerilog((context, services, configuration) => configuration 
    .MinimumLevel.Information() 
    .ReadFrom.Configuration(context.Configuration) 
    .ReadFrom.Services(services) 
    .Enrich.FromLogContext() 
    .WriteTo.ApplicationInsights(appInsightConnection, TelemetryConverter.Traces, LogEventLevel.Information);

当我在try...catch块中调用Log.Error(ex, ex.Message)时,异常并未记录到Application Insights,但Log.Information的内容可以正常记录。

我理解若设置最低日志级别为Information,高于该级别的日志(包括异常)都应被记录,但实际并非如此。我尝试设置MinimumLevel为Information,期望所有高于该级别的日志(含异常)都能发送至Application Insights,但只有Log.Information的跟踪消息被记录。

我的观察结果如下:

  • 当.WriteTo.ApplicationInsights()中的LogEventLevel设为Information时,Log.Information的内容可正常记录,但异常无法记录。
  • 当LogEventLevel设为Error时,Log.Error可记录异常,但Log.Information的跟踪消息无法记录。
解决方案

问题出在你使用的TelemetryConverter.Traces上——这个转换器只会把日志事件转换成跟踪遥测(Trace Telemetry),而Serilog的Log.Error(ex, ...)生成的异常信息,需要用TelemetryConverter.TracesAndExceptions才能同时捕获跟踪消息和异常详情并写入Application Insights。

另外要注意,不要在WriteTo.ApplicationInsights的级别参数上做过严限制,正确的做法是保留级别为LogEventLevel.Information,配合合适的转换器即可。

修改后的配置代码如下:

builder.Host.UseSerilog((context, services, configuration) => configuration 
    .MinimumLevel.Information() 
    .ReadFrom.Configuration(context.Configuration) 
    .ReadFrom.Services(services) 
    .Enrich.FromLogContext() 
    // 使用TracesAndExceptions转换器,同时保留级别为Information
    .WriteTo.ApplicationInsights(appInsightConnection, TelemetryConverter.TracesAndExceptions, LogEventLevel.Information);

如果需要更精细的控制,也可以分开配置两个Application Insights写入器:

builder.Host.UseSerilog((context, services, configuration) => configuration 
    .MinimumLevel.Information() 
    .ReadFrom.Configuration(context.Configuration) 
    .ReadFrom.Services(services) 
    .Enrich.FromLogContext() 
    // 处理Information及以上的跟踪消息
    .WriteTo.ApplicationInsights(appInsightConnection, TelemetryConverter.Traces, LogEventLevel.Information)
    // 处理Error及以上的异常事件
    .WriteTo.ApplicationInsights(appInsightConnection, TelemetryConverter.Events, LogEventLevel.Error);

额外检查项:

  • 确保你的Serilog.Sinks.ApplicationInsights包是最新版本,旧版本可能存在转换器的兼容性问题。
  • 确认Application Insights的连接字符串appInsightConnection配置正确,且拥有写入遥测数据的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 04:17:38