Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core logging in 2 different files

When using the default ASP.NET core logging in combination with Serilog, is it possible to write errors to errors.log and information to informations.log

using Microsoft.Extensions.Logging;
using Serilog;

loggerFactory.AddSerilog();
loggerFactory.AddFile(Configuration.GetSection("Logging"));

Appsettings.json:

"Logging": {
    "PathFormat": "path-{Date}.log",
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "System": "Information",
      "Microsoft": "Information"
    }
  }

I want one logging file where I can see the requests which are done and stuff like that, just the info log. And one log with errors for debugging purposes. How can I log different things to 2 files?

like image 471
Roboneter Avatar asked Mar 06 '23 02:03

Roboneter


1 Answers

If you want to use a single Logger object you can filter log type by level:

using Serilog;
using Serilog.Events;

Log.Logger = new LoggerConfiguration()
            // Restricts logs to: Debug, Information, Warning, Error and Fatal
            .MinimumLevel.Debug()
            // Logs Information, Warning, Error and Fatal to "info-logs.txt" file
            .WriteTo.File(path: "info-logs.txt", restrictedToMinimumLevel: LogEventLevel.Information)
            // Logs Error and Fatal to "error-logs.txt" file
            .WriteTo.File(path: "error-logs.txt", restrictedToMinimumLevel: LogEventLevel.Error) 
            .CreateLogger();

Log.Verbose("Loggin Verbose..."); // Won't log, because the Logger "MinimumLevel" is set to Debug
Log.Debug("Loggin Debug..."); // Won't log, because there is no sink that takes Debug
Log.Information("Loggin Information..."); // Logs into "info-logs.txt"
Log.Warning("Loggin Warning..."); // Logs into "info-logs.txt"
Log.Error("Loggin Error..."); // Logs into "info-logs.txt" and "error-logs.txt"
Log.Fatal("Loggin fatal..."); // Logs into "info-logs.txt" and "error-logs.txt"

The log levels and descriptions from the docs:

enter image description here

like image 167
LucaSC Avatar answered Mar 07 '23 17:03

LucaSC