.NET 6中如何忽略ILogger日志与健康检查的OpenTelemetry追踪
解决方案
过滤健康检查请求
AspNetCoreInstrumentation默认会捕获所有HTTP请求,包括健康检查端点(如/healthz、/health)。要排除这些请求,可在AddAspNetCoreInstrumentation中配置过滤规则:
b.AddAspNetCoreInstrumentation(options => { options.Filter = context => { // 根据实际健康检查路径调整判断条件 return !context.Request.Path.StartsWithSegments("/health") && !context.Request.Path.StartsWithSegments("/healthz") && !context.Request.Path.StartsWithSegments("/ready"); }; })
停止ILogger日志发送到Jaeger
如果ILogger日志被同步到Jaeger,通常是因为配置了OpenTelemetry日志导出,或者日志被附加到追踪Span中,可通过以下方式处理:
移除日志导出配置:
检查项目中是否存在WithLogging并添加了AddOtlpExporter的代码,若无需将日志发送到Jaeger,直接移除该部分配置即可。过滤日志事件:
如果日志被附加到Span事件中,可通过Enrich方法移除不需要的日志属性:
b.AddAspNetCoreInstrumentation(options => { // ... 其他配置 options.Enrich = (activity, eventName, rawObject) => { if (eventName == "OnLog") { // 移除所有以log.开头的Span标签 foreach (var key in activity.Tags.Keys.Where(k => k.StartsWith("log.")).ToList()) { activity.Tags.Remove(key); } } }; })
- 日志级别过滤:
若仍需保留部分日志导出,可通过日志过滤规则屏蔽健康检查及无关日志:
services.AddOpenTelemetry() .WithLogging(b => { b.AddFilter("Microsoft.AspNetCore.Diagnostics.HealthChecks", LogLevel.None); b.AddFilter("*", LogLevel.Warning); // 仅保留Warning及以上级别的日志 // 若不需要日志发送到Jaeger,移除b.AddOtlpExporter() });
完整示例代码
services.AddOpenTelemetry() .ConfigureResource(configureResource) .WithTracing(b => { b.AddAspNetCoreInstrumentation(options => { // 过滤健康检查请求 options.Filter = context => !context.Request.Path.StartsWithSegments("/health") && !context.Request.Path.StartsWithSegments("/healthz") && !context.Request.Path.StartsWithSegments("/ready"); // 移除日志相关的Span标签 options.Enrich = (activity, eventName, rawObject) => { if (eventName == "OnLog") { foreach (var key in activity.Tags.Keys.Where(k => k.StartsWith("log.")).ToList()) { activity.Tags.Remove(key); } } }; }) .AddHttpClientInstrumentation() .AddSqlClientInstrumentation() .AddOtlpExporter(options => { options.Endpoint = new Uri("http://localhost:4317"); }); });
内容的提问来源于stack exchange,提问作者Hamid Noahdi
相关产品推荐
相关产品推荐

