Reputation: 2401
I'm logging events for all types (information, error, debug, etc.) in an asp.net core 3.1 project, but I need to separate logs files according to the LogLevel. errors.log file will store LogLevels such as Error, Fatal and Warning, and information.log will store LogLevels such as Information and Debug.
This is the configuration in appSettings.json file:
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/errors_.log",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"fileSizeLimitBytes": 1024000,
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "(@Level = 'Information' or @Level = 'Debug')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/information_.log",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"fileSizeLimitBytes": 1024000,
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName"
],
"Properties": {
"Application": "SicotX"
}
This is the program.cs:
public class Program
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddJsonFile($"appsettings.{Environment.MachineName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
public static void Main(string[] args)
{
var host = CreateHost(args);
// ======================================================================================================
// See configuration details in appsettings.json
// Verbose: Verbose is the noisiest level, rarely(if ever) enabled for a production app.
// Debug: Debug is used for internal system events that are not necessarily observable from the outside,
// but useful when determining how something happened.
// Information: Information events describe things happening in the system that correspond to its responsibilities
// and functions.Generally these are the observable actions the system can perform.
// Warning: When service is degraded, endangered, or may be behaving outside of its expected parameters, Warning level events are used.
// Error: When functionality is unavailable or expectations broken, an Error event is used.
// Fatal: The most critical level, Fatal events demand immediate attention.
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
try
{
Log.Logger.Information("Creating the web host ...");
host.Run();
Log.Logger.Information("Shutting down the web host ...");
}
catch (Exception e)
{
Log.Logger.Fatal(e, "A fatal error ocurred creating the web host.");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHost CreateHost(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, config) =>
{
config.ClearProviders();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseSerilog()
.Build();
}
No matter if MinimunLevel/Default is "Information" or "Error", both files, information_.log and errors_.log files are created and logs are reported in both files. There's not separation of information type. Following is a part of the content of the information_log file as a sample to show that info logs and errors logs are mixed in the same file:
I log errors by using _logger.Error(...) and information by using _logger.Information(...).
How can I do to filter and log data according LogLevel in the corresponding file?.
Thanks
Upvotes: 1
Views: 889
Reputation: 2401
I've found the solution!
On one hand, I was missing the nuget package Serilog.Expressions that enables Filter args expressions.
On the other hand, latest versions of serilog use the expression @1 instead of @Level, so the filter should be like this:
"Args": {
"expression": "@l in ['Error', 'Fatal', 'Warning']"
}
Now, the type level of log is sent to the right type of file.
Upvotes: 5