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

源代码生成日志未写入Application Insights的问题排查

解决自定义LoggerMessage日志无法发送到Application Insights的问题

可能的原因及修复步骤

1. 确认Serilog已注册为ILogger的默认提供程序

如果仅配置了Serilog的日志输出,但未将其设置为ASP.NET Core应用的默认ILogger提供程序,微软ILogger(包括LoggerMessage生成的自定义方法)可能会使用其他日志提供程序,导致日志未进入Serilog的处理链路。

在Program.cs中添加Serilog注册代码:

var builder = WebApplication.CreateBuilder(args);

// 初始化TelemetryConfiguration
var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.ConnectionString = builder.Configuration.GetConnectionString("ApplicationInsights") 
    ?? throw new InvalidOperationException("Application Insights连接字符串缺失!");

// 配置Serilog并设置为应用日志提供程序
var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Traces)
    .CreateLogger();

// 将Serilog设置为默认日志提供程序
builder.Host.UseSerilog(logger);

2. 修正LoggerMessage模板,包含Exception占位符

你的LogErrorDetailed方法参数包含Exception,但日志模板中未添加{Exception}占位符,这会导致异常信息无法被日志系统正确捕获,甚至可能影响日志的级别识别。修改模板如下:

[LoggerMessage(LogLevel.Error, Message = "{message} - {sourceFilePath} in method: {methodName} line: {lineNumber}{Exception:ToString}")]
public static partial void LogErrorDetailed(this ILogger logger,
    string message,
    Exception exception,
    [CallerMemberName] string methodName = "",
    [CallerLineNumber] int lineNumber = 0,
    [CallerFilePath] string sourceFilePath = "");

添加{Exception:ToString}可以完整输出异常堆栈信息,确保Error级别的日志能被Serilog和Application Insights正确识别。

3. 检查自定义日志的调用方式

确保调用LogErrorDetailed时正确传入了Exception参数,避免传入null(虽然Error级别日志即使无异常也应被捕获,但完整的异常信息有助于AI的错误跟踪):

try
{
    // 业务代码
}
catch (Exception ex)
{
    _logger.LogErrorDetailed("发生错误", ex);
}

4. 验证Serilog配置的日志级别

确认appsettings.json中的Serilog最低级别设置能覆盖自定义日志的类别:

"Serilog": {
  "MinimumLevel": {
    "Default": "Information",
    "Override": {
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

Default: "Information"会包含Error级别日志,无需额外调整,除非你为自定义日志的类别单独设置了Override规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:20:19