2

Currently all the tasks records create in a one log file. I want to create separate log file for each tasks rather than one log file. (Currently log file contains batch jobs)

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.RollingFile.Extension" ],
    "MinimumLevel": {
      "Default": "Warning",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "rollingInterval": "Day",
          "fileSizeLimitBytes": 10485760,
          "pathFormat": "RDJOBS_{Date}_{Level}.json",
          "path": "c://logs",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      },
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "http://localhost:5421"
        }
      }
    ]
  }
}
SA_VL
  • 31
  • 4
  • 1
    Does this answer your question? [Serilog : Log to different files](https://stackoverflow.com/questions/38481227/serilog-log-to-different-files) – gunr2171 Sep 01 '21 at 12:20
  • No, its not. I don't want to create separate log files base on the levels. I want separate log files base on the task as if in the log files logs created on base on several tasks or classes behavior. So I want to separate log files base on that tasks or the classes, not on the level. – SA_VL Sep 02 '21 at 02:41
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 04 '21 at 09:27
  • **Problem –** I want to create individual log files for tasks or classes using serilog and respective configurations must do on appsetting.json file. **Current situation –** As answer provided by @ZhiLv (below answer) can be solve the problem. But in that solution, all the configuration done on program.cs file. But I needed configuration on appsetting.json file. **Highlights –** Need to create separate log files base on the classes or tasks not on the log event level. Need to do all the configuration on the appsetting.json file. – SA_VL Sep 07 '21 at 07:36

1 Answers1

1

You can use the Filter.ByExcluding() and Filter.ByIncludingOnly() to add filter expression to filter events passing through the Serilog pipeline, for each task or class, when you use them, you can set a property for them, then use the filter expression to filter the log and write to a different log file.

For demo purposes, we can set a property to the LogEvents in this method execution path.

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Worker is called");
        using (LogContext.PushProperty("foobar", 1))
        {
            Foo();
            await Task.CompletedTask;
        }
    }

The following code snippet shows a filtering example.

const string logTemplate = @"{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u4}] [{SourceContext:l}] {Message:lj}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
        .Enrich.FromLogContext()
        .WriteTo.Logger(l =>
        {
            l.WriteTo.File("log.txt", LogEventLevel.Information, logTemplate,
                rollingInterval: RollingInterval.Day
            );
            l.Filter.ByExcluding(e => e.Properties.ContainsKey("foobar"));
        })
        .WriteTo.Logger(l =>
        {
            l.WriteTo.File("foobar.txt", LogEventLevel.Information, logTemplate,
                rollingInterval: RollingInterval.Day
            );
            l.Filter.ByIncludingOnly(e => e.Properties.ContainsKey("foobar"));
        })
        .CreateLogger()

With the configuration above, normal logs (without the property foobar in log events) will be saved to the log.txt file, while logs with the property foobar will be saved to the foobar.txt file.

After running the application, the result as below:

enter image description here

More detail information, check this sample.

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
  • Thanks for supper helpful detailed answer – SA_VL Sep 03 '21 at 07:48
  • Is it possibele to do all the configuration on the appsetting.json rather than on the program.cs and achieve the same? – SA_VL Sep 07 '21 at 07:46
  • 2
    From the [serilog document](https://github.com/serilog/serilog-settings-configuration): A Serilog settings provider that reads from Microsoft.Extensions.Configuration sources, including .NET Core's appsettings.json file. And it contains the [Filter section](https://github.com/serilog/serilog-settings-configuration#filter-section) to filter log events. So it is possible to do it on the appsetting.json file, but I'm not familiar it, you can have a try, if there have any question, you can post the problem on [Serilog forum](https://github.com/serilog/serilog-settings-configuration/issues). – Zhi Lv Sep 07 '21 at 08:51