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

如何从C# K8s容器应用向Application Insights正确实现日志记录

手动向Application Insights发送指定日志的简单方案(.NET 6 + Azure K8s)

1. 确认依赖包已安装

确保项目引用以下NuGet包:

  • Microsoft.ApplicationInsights.AspNetCore(Application Insights核心集成包)
  • Serilog.Sinks.ApplicationInsights(Serilog向AI发送日志的适配包)

2. 修正Program.cs配置

调整Serilog初始化时机,确保在WebApplication构建完成后获取TelemetryConfiguration;若要使用ASP.NET Core原生ILogger接口,需将Serilog设为默认日志提供器。完整示例:

var builder = WebApplication.CreateBuilder(args);

// 添加Application Insights服务
builder.Services.AddApplicationInsightsTelemetry();

// 添加控制器视图服务
builder.Services.AddControllersWithViews();

// 可选:将Serilog设为ASP.NET Core默认日志提供器(使用ILogger时需添加)
builder.Host.UseSerilog();

// 构建应用实例
var app = builder.Build();

// 初始化Serilog并关联Application Insights
Log.Logger = new LoggerConfiguration()
    .WriteTo.ApplicationInsights(
        app.Services.GetRequiredService<TelemetryConfiguration>(),
        TelemetryConverter.Traces)
    .CreateLogger();

// 保留原有中间件配置
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

3. 手动发送日志的两种方式

方式一:Serilog静态类直接发送(快捷简单)

在任意需要记录日志的代码位置,直接调用Serilog静态方法:

// 发送普通信息日志
Log.Information("用户完成支付操作,订单ID:{OrderId}", 1001);

// 发送带异常栈的错误日志
try
{
    // 业务逻辑代码
}
catch (Exception ex)
{
    Log.Error(ex, "支付操作失败,订单ID:{OrderId}", 1001);
}

方式二:ASP.NET Core ILogger接口(符合依赖注入规范)

在控制器或服务类中注入ILogger<T>,在指定位置调用日志方法:

public class PaymentController : Controller
{
    private readonly ILogger<PaymentController> _logger;

    // 构造函数注入ILogger
    public PaymentController(ILogger<PaymentController> logger)
    {
        _logger = logger;
    }

    public IActionResult Complete()
    {
        // 支付完成后手动记录日志
        _logger.LogInformation("支付流程结束,用户ID:{UserId}", "user_007");
        
        // 记录异常场景日志
        _logger.LogError("支付回调验证失败,回调地址:{CallbackUrl}", Request.Path);
        
        return View();
    }
}

4. 配置Application Insights连接信息

推荐使用连接字符串配置,支持两种方式:

  • 配置文件方式:在appsettings.json中添加:
{
  "ApplicationInsights": {
    "ConnectionString": "你的Application Insights连接字符串"
  }
}
  • K8s环境变量方式:在Pod的环境变量中设置APPLICATIONINSIGHTS_CONNECTION_STRING,无需修改代码配置,更适合容器化部署。

5. 验证日志投递

部署到K8s后,进入Azure门户的Application Insights资源,在日志页面执行Kusto查询:

traces
| where message contains "你设置的日志关键词"
| order by timestamp desc

即可看到手动发送的日志条目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:54:22