No *_*o U 6 c# serilog .net-core
我正在.NET Core 应用程序中注入类型化 HTTP 客户端。我也在使用 Serilog 进行日志记录。我没有特意配置任何 HTTP 活动日志记录。它神奇地随之而来。我该如何关闭此功能?
[12:00:52 INF] Start processing HTTP request POST https://foo/bar
[12:00:52 INF] Sending HTTP request POST https://foo/bar
[12:00:53 INF] Received HTTP response after 707.8906ms - OK
Run Code Online (Sandbox Code Playgroud)
我的 HTTP 客户端配置:
services.AddHttpClient("FOO")
.ConfigureHttpClient(client =>
{
client.BaseAddress = new Uri("https://foo/");
})
.ConfigurePrimaryHttpMessageHandler(sp => new HttpClientHandler()
{
Credentials = new NetworkCredential("user", "pass"),
ServerCertificateCustomValidationCallback = (senderC, cert, chain, sslPolicyErrors) => true
})
.AddTypedClient<Thing1>()
.AddTypedClient<Thing2>();
Run Code Online (Sandbox Code Playgroud)
我遇到了这个问题,并能够使用 Serilog 的Filter配置来解决。不确定在哪里记录(这似乎是相关的),但一种途径是实现ILogEventFilter接口(源代码)。包括允许事件的逻辑,并插入配置中。
过滤器类示例:
public class MyLoggingFilter : ILogEventFilter
{
private static readonly HashSet<string> ignoredMessages = new HashSet<string>(StringComparer.Ordinal)
{
"Start processing HTTP request {HttpMethod} {Uri}",
"End processing HTTP request after {ElapsedMilliseconds}ms - {StatusCode}"
};
// Allow the event to be logged if the message template isn't one we ignore
public bool IsEnabled(LogEvent logEvent) => !ignoredMessages.Contains(logEvent.MessageTemplate.Text);
}
Run Code Online (Sandbox Code Playgroud)
添加到配置(在本例中为 Program.cs):
config
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Filter.With<MyLoggingFilter>() // <-- Plug in your filter type
.WriteTo.Console(theme: AnsiConsoleTheme.Code)
.WriteTo.Debug()
// etc
Run Code Online (Sandbox Code Playgroud)
或者,如果您想阻止与 HttpClient 相关的任何日志记录,请使用所需的日志级别覆盖类别(即类型命名空间):
config.MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4109 次 |
| 最近记录: |