如何将.NET Core应用集成至Azure Kubernetes集群Container Insights查看日志
.NET Core API集成Azure Kubernetes Container Insights日志配置指南
一、捕获并输出错误与异常的代码更改
- 添加全局异常中间件:在API中新增全局异常中间件,捕获所有未处理的异常并记录详细上下文信息,同时返回统一的错误响应。示例代码如下:
public class GlobalExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<GlobalExceptionMiddleware> _logger; public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) { _logger.LogError(ex, "未处理异常 - 请求路径: {RequestPath}, 请求方法: {RequestMethod}", httpContext.Request.Path, httpContext.Request.Method); httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; await httpContext.Response.WriteAsJsonAsync(new { Message = "服务器内部错误" }); } } } // 在Program.cs中注册中间件 app.UseMiddleware<GlobalExceptionMiddleware>();
- 启用结构化JSON日志输出:将控制台日志改为JSON格式,方便Container Insights解析和查询。修改
Program.cs的日志配置:
builder.Logging.ClearProviders(); builder.Logging.AddConsole(options => { options.FormatterName = "json"; }).AddConsoleFormatter<JsonConsoleFormatter, JsonConsoleFormatterOptions>(options => { options.IncludeScopes = true; options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff"; });
- 主动记录业务异常:在业务逻辑的关键节点(如数据库操作、外部API调用)主动捕获异常,使用
LogError或LogCritical记录带上下文的日志,便于问题定位:
try { // 执行数据库更新操作 await _dbContext.SaveChangesAsync(); } catch (DbUpdateException ex) { _logger.LogError(ex, "数据库更新失败 - 实体ID: {EntityId}, 操作类型: {OperationType}", entity.Id, "Update"); throw; }
二、已知WriteTo.Console()被K8s捕获时的额外配置
- 配置合理的日志级别:在
appsettings.json中设置日志级别,确保错误、异常类日志被完整输出,避免遗漏关键信息:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "YourAppNamespace.Api": "Debug" } } }
- 注入Kubernetes元数据到日志:通过环境变量获取Pod名称、命名空间等K8s元数据,将其加入日志上下文,方便在Container Insights中过滤和定位特定Pod的日志:
// 在Program.cs中添加日志上下文支持 builder.Services.AddHttpContextAccessor(); // 在中间件或业务代码中使用日志范围注入元数据 var podName = Environment.GetEnvironmentVariable("POD_NAME"); var podNamespace = Environment.GetEnvironmentVariable("POD_NAMESPACE"); using (_logger.BeginScope(new Dictionary<string, object> { ["PodName"] = podName, ["Namespace"] = podNamespace })) { _logger.LogInformation("请求处理完成 - 路径: {Path}", httpContext.Request.Path); }
- 确保日志字段完整性:确认JSON日志包含
Timestamp、Level、Message、Exception等核心字段,Container Insights会自动识别这些字段,支持后续的日志查询、筛选和可视化分析。
内容的提问来源于stack exchange,提问作者Hemanth Reddy
相关产品推荐
相关产品推荐

