I've been asked to write log levels Information, Warning and Error in development, but each of them in one separated file, so that I have information.txt
containing only Information logs, warning.txt
containing only Warning logs, Error.txt
containing only Error logs.
This is my implementation at the moment (it works).
In Program.cs
:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseSerilog((webHostBuilderContext, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(webHostBuilderContext.Configuration);
});
});
In appsettings:
"Serilog": {
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "wwwroot/Logs/log.txt",
"rollingInterval": "Day",
"reatinedFileCountLimit": 14,
"restrictedToMinimumLevel": "Information"
}
}
]
},
I have installed Serilog.Expressions package and read the docs, I know I have to use something like this
"Filters": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@l = 'Information'"
}
}
]
but I can't understand where it should be placed. I've tried placing it in Args
or between Args
and Name
but it doesn't work, can somebody help me?
I already read lots of threads here on stackoverflow but nothing worked :(
This works but not use doc.
using Serilog;
using Serilog.Events;
Log.Logger = new LoggerConfiguration()
.WriteTo.Logger(l => l
.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information)
.WriteTo.File(
path: "information.txt"))
.WriteTo.Logger(l => l
.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
.WriteTo.File(
path: "error.txt"))
.CreateLogger();
Log.Information("test Information");
Log.Error("test Error");
---------------update using appsettings.json--------------
install package Serilog.Expressions
"Serilog": {
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@l = 'Information'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "information.txt"
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@l = 'Error'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "error.txt"
}
}
]
}
}
}
]
}
Test Result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With