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

浪子不回头ぞ 提交于 2021-01-01 09:34:54

问题


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 ;
    }

回答1:


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();



回答2:


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();


来源:https://stackoverflow.com/questions/61996512/serilog-separate-files-for-information-exception-using-appsetting-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!