Serilog - Separate files for Information, exception using appsetting.json

2.3k Views Asked by At

I am writing all logs into one file(s) using rolling. But I want to separate them by Information, Warning and Exceptions rolling files.

my current configuration is like this

     "Serilog": {
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\log-{Hour}.log",
          "rollOnFileSizeLimit ": true,
          "retainedFileCountLimit ": null,
          "rollingInterval": "Hour",
          "fileSizeLimitBytes": 5000000
        }
      }
    ]
  },

class

public ILogger GetLogger()
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        _logger =
            new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

        return _logger ;
    }
2

There are 2 best solutions below

3
On

i have not tested but by extrapoling the documentation: you could try to create 2 sections in you appconf file

  "ErrorLog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\ Errorlog-{Hour}.log",       
          "rollingInterval": "Hour",
          "restrictedToMinimumLevel": "Error"
        }
      }
    ]
  },
  "InfoLog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\ Infolog-{Hour}.log",
          "rollingInterval": "Hour",
          "restrictedToMinimumLevel": "Information"
        }
      }
    ]
  }

and you create 2 loggers:

    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();


        var errorSection = configuration.GetSection("ErrorLog");
        var infoSection = configuration.GetSection("InfoLog");


        _errorlog = new LoggerConfiguration()
            .ReadFrom
            .ConfigurationSection(errorSection)
            .CreateLogger();

        _infolog = new LoggerConfiguration()
            .ReadFrom
            .ConfigurationSection(infoSection)
            .CreateLogger();
1
On

In Serilog you could do this separation either via sub-loggers or via Serilog.Sinks.Map.

You wouldn't be able to configure the whole pipeline via appsetting.json but you can easily configure the path of each file in appsetting.json using a custom key of your choice, and use that when configuring the log pipeline via code.


Example using sub-loggers with a filter applied to each of them:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
            .WriteTo.File("Debug.log"))
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
            .WriteTo.File("Error.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();

Example using Serilog.Sinks.Map mapping each LogEventLevel to a different file.

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Map(evt => evt.Level, (level, wt) => wt.File($"{level}.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();