Azure Function中LogCritical日志为何写入AppTraces而非AppExceptions?
问题原因
默认情况下,Microsoft.Extensions.Logging对接Application Insights的提供器,会把所有通过ILogger.LogXXX方法输出的日志(即使携带Exception参数)统一作为跟踪日志写入AppTraces表,只有显式调用异常追踪接口的日志才会写入AppExceptions表。
解决方案
方案1:修改全局配置(推荐)
你可以通过配置ApplicationInsightsLoggerOptions的TrackExceptionsAsExceptionTelemetry属性为true,让所有携带Exception参数的日志自动作为异常遥测写入AppExceptions表。
Azure Function配置步骤:
- 安装对应NuGet包(如果未安装):
Microsoft.Extensions.Logging.ApplicationInsights,版本要求≥2.15.0 - 在Function的启动配置类(继承
FunctionsStartup的类)中添加如下配置:
using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.ApplicationInsights; [assembly: FunctionsStartup(typeof(YourNamespace.YourStartupClass))] namespace YourNamespace { public class YourStartupClass : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { builder.Services.Configure<ApplicationInsightsLoggerOptions>(options => { options.TrackExceptionsAsExceptionTelemetry = true; }); } } }
配置完成后,你现有代码中的log.LogCritical(ex, ex.Message)调用就会自动写入AppExceptions表,同时也会保留对应的日志级别等属性。
方案2:显式调用异常追踪接口
如果你不想修改全局配置,可以直接注入TelemetryClient,在捕获异常时调用TrackException方法:
- 注入TelemetryClient到你的Function方法参数中:
public static void Run(IService service, ILogger log, bool throwException, bool addHeartBeat = false, TelemetryClient telemetryClient)
- 修改catch块的代码:
catch (Exception ex) { // 记录异常到AppExceptions表 telemetryClient.TrackException(ex); // 可选:保留原日志逻辑记录到AppTraces log.LogCritical(ex, ex.Message); if (throwException) { // 注意这里不要用throw ex,会丢失原始栈信息,直接用throw即可 throw; } }
注意:原有代码中
throw ex的写法会重置异常的调用栈信息,排查问题时无法获取原始异常的抛出位置,建议改为直接使用throw语句。
内容的提问来源于stack exchange,提问作者Thomas Segato
相关产品推荐
相关产品推荐

