WEB API, .NET CORE, C#, NET 8.0, SERILOG, SINK FILE, SERILOG EXPRESSIONS
Good morning,
as per demo attached here (https://github.com/serilog/serilog-sinks-file/issues/317) I have some problem to write logs filtering by a certain Context by using the appsettings.json
It write everything with every types of context.
ex.Controller API
`Log.ForContext("logtype", "pippo").Information("This is a pippo log");`
THIS IS THE EXAMPLE THAT DOESN’T WORK
Program.cs
`var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).Build();
// Configura Serilog utilizzando la configurazione
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();`
appsettings.json
`"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Expressions" ], //"Serilog.Filters.Expressions",
"MinimumLevel": "Debug",
"Enrich": [ "FromLogContext" ],
"WriteTo": [
//{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "logs/log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff}Z - {Properties:j}
{SourceContext} {Level:u3} {Message:lj}{NewLine}{Exception}"
},
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
//"expression": "Contains(@p['logtype'],'pippo')"
//"expression": "@p['logtype'] is null"
//"expression": "(@Properties['logtype'] == 'pippo')"
"expression": "Contains(@Properties['logtype'], 'pippo')"
//"expression": "Equals(@Properties['logtype'], 'pippo')"
//"expression": "logtype='pippo'"
}
}
]
}
]
}`
BUT if I configure serilog in the Program.cs without the appsettings.json it works
THIS EXAMPLE WORKS
` Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.WithProperty<string>("logtype", p => p == "pippo"))
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff}Z - {Properties:j} {SourceContext} {Level:u3} {Message:lj}{NewLine}{Exception}"))
.CreateLogger();
builder.Host.UseSerilog();`
Stefania is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.