I have a a webapp using the terse .NET 6/7 serilog initialization:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, lc) => {
lc.WriteTo.File(
logDir "\\mylog.log"
).Filter.ByExcluding(le => {
var s = le.RenderMessage();
return s.StartsWith("Executing endpoint")
|| s.StartsWith("Executed endpoint")
|| s.StartsWith("User logged in.");
});
});
I now want to filter some messages:
AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Debug);
AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Debug);
However I am not sure how to plug these AddFilter
statements into the above builder
Any help ?
CodePudding user response:
If you want to omit the Microsoft.Namespace log. The JSON configuration to do this looks like this:
You need to install Serilog.Filters.Expressions
nuget package
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.EntityFrameworkCore": "Information"
}
},
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "StartsWith(SourceContext, 'Microsoft.EntityFrameworkCore')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\LOGS\\TestService_EF_.json",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}
}
]
}
CodePudding user response:
For a code based approach, use MinimumLevel.Override
builder.UseSerilog(
(ctx, lc) => lc
.WriteTo.File(logDir "\\mylog.log")
.Filter.ByExcluding(le => {
var s = le.RenderMessage();
return s.StartsWith("Executing endpoint")
|| s.StartsWith("Executed endpoint")
|| s.StartsWith("User logged in.");
})
.MinimumLevel.Override("Microsoft.AspNetCore.SignalR", Serilog.Events.LogEventLevel.Debug)
.MinimumLevel.Override("Microsoft.AspNetCore.Http.Connections", Serilog.Events.LogEventLevel.Debug)
);
For a configuration approach, use ReadFrom.Configuration
builder.UseSerilog(
(ctx, lc) => lc
.WriteTo.File(logDir "\\mylog.log")
.Filter.ByExcluding(le => {
var s = le.RenderMessage();
return s.StartsWith("Executing endpoint")
|| s.StartsWith("Executed endpoint")
|| s.StartsWith("User logged in.");
})
.ReadFrom.Configuration(ctx.Configuration)
);
Your appsettings.json
file should look something like below.
The log levels might be different.
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning"
}
},
"Serilog": {
"MinimumLevel": {
"Default": "Warning",
"Override": {
"Microsoft.AspNetCore.SignalR": "Debug",
"Microsoft.AspNetCore.Http.Connections": "Debug"
}
}
}
}