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

