【发布时间】:2021-02-26 12:30:49
【问题描述】:
请参阅下面的示例,默认 ASP.NET Core 日志记录设置,其中默认 loglevel 是“信息”,但对于 ApplicationInsights,Microsoft 命名空间的 loglevel 是警告:
"Logging": {
"LogLevel": {
"Default": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
}
}
这很有用,例如,我不想将健康请求记录到 App Insights。不将它们发送到 App Insights 会导致费用减少!
现在,我真的不知道如何使用Serilog 做到这一点。我使用控制台和应用程序洞察接收器。 minimumLevel 似乎是为整个 serilog 记录器配置的,而不是基于接收器。
编辑:我已经放弃了这件事,因为它对我的用例来说太复杂了!
我已经放弃了尝试使用 Serilog 来实现这一点,因为 .net 5.0 日志记录已经改进了很多;我不再需要 Serilog。
我已经实现了不使用以下代码将健康请求记录到 App Insights 的愿望:
"Logging": {
"LogLevel": {
"Default": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"IdentityServer4.AccessTokenValidation": "Warning",
"System.Net.Http.HttpClient": "Warning"
}
},
"Console": {
"FormatterName": "Simple",
"LogLevel": {
"Default": "Information"
},
"FormatterOptions": {
"SingleLine": false,
"TimestampFormat": "[yyyy-MM-ddThh:mm:ss] "
}
}
},
添加IdentityServer4.AccessTokenValidation 和System.Net.Http.HttpClient 是因为它们会记录一些我在App Insights 中不需要的信息,因为它们已经记录为Request。
如有必要,控制台将记录所有内容以进行更清晰和更深入的调试。
此外,为了防止 App Insights 仍然每隔几秒保存一次“健康”请求,我使用了this blog post from Jim Aho 来防止 App Insights 保存某些请求。请注意,我确实使用了一些 null 检查,因为有时 URL 可能为 null,具体取决于遥测。
/// <summary>
/// Stops certain requests from being logged to App Insights to prevent noise and save money.
/// </summary>
/// <remarks>
/// Based on https://blog.steadycoding.com/azure-application-insights-without-noise-from-health-checks-and-swagger/
/// </remarks>
public class IgnoreRequestPathsTelemetryProcessor : ITelemetryProcessor
{
private readonly ITelemetryProcessor _next;
private readonly IEnumerable<string> _pathsToIgnore = new[]
{
"/health",
"/swagger"
};
private static readonly StringComparison _stringComparison = StringComparison.InvariantCultureIgnoreCase;
public IgnoreRequestPathsTelemetryProcessor(ITelemetryProcessor next)
{
_next = next;
}
public void Process(ITelemetry item)
{
if (ShouldFilterOutTelemetry(item))
{
return;
}
_next.Process(item);
}
private bool ShouldFilterOutTelemetry(ITelemetry item)
{
return item is RequestTelemetry request && _pathsToIgnore.Any(x => request.Url?.AbsolutePath?.StartsWith(x, _stringComparison) == true);
}
}
【问题讨论】:
-
我认为您想要 Serilog 的子记录器功能。但是没有用过,我不能肯定
-
@pinkfloydx33 嗯,这是我可以尝试的,虽然它看起来相当麻烦。我会试试这个!如果其他人遇到此问题,如果该解决方案有效,我不回复,请提醒我回复:)。
-
下面的答案有帮助吗?
-
你好。谢谢您的帮助。我决定不再继续使用 Serilog;自从改进了 .net 5.0 的登录后,它的收益微乎其微,所以我切换到了这个。为不同接收器的命名空间设置不同的日志级别似乎比基本的 .net 5.0 日志记录要复杂得多。此外,我使用了blog.steadycoding.com/… 来防止 App Insights 记录我不需要的请求。
标签: c# .net asp.net-core azure-application-insights serilog