0

Im using Serilog to log to a file:

"WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "serilog\\applicationlog.txt",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 4194304,
          "retainedFileCountLimit": 10,
          "rollingInterval": "Infinite",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
          "shared": false
        }
      },

What I need is to change the Args -> Path property dynamically on the code before doing some logging. So by default, it will use the appsettings.json value but some logging might want to use a different file.

For example:

I want this logging to go to a different file:

// Test for Serilog with dynamic file path.
LogContext.PushProperty("CustomUserName", model.Login);

//** HERE I WANT TO CHANGE THE FILE PATH DYNAMICALLY **//

_logger.LogError(new Exception("Manual exception created for testing."), "This is a warning test onlY.");

Any clue?

VAAA
  • 14,531
  • 28
  • 130
  • 253

1 Answers1

0

You can have two writeTo File configurations, just add "restrictedToMinimumLevel": "Error" to send errors only to the other file

"WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "c:/temp/Logging.App.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "c:/temp/Logging.App.Errors.log",
          "restrictedToMinimumLevel": "Error",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Message}{NewLine}{Exception}"
        }
      }
    ]

adapted from https://stackoverflow.com/a/73823173

Jyri
  • 36
  • 3