Search code examples
c#serilog

Serilog: Log to file only in development


I'm looking for a way to configure Serilog for my .NET console app so that it logs to a local file only when developing locally. Currently it's configured for Seq in my appsettings.json:

"Serilog": {
    "MinimumLevel": {
      "Default": "Warning",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "https://some/url",
          "apiKey": "aKey",
          "batchPostingLimit": "500"
        }
      },
      {
        "Name": "debug"
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ]
  },

Currently, in the code, I have this:

Log.Logger = new LoggerConfiguration()
                   .ReadFrom.Configuration(configuration)
                   .Enrich.WithProperty("MachineName", Environment.MachineName)
                   .CreateLogger();

Is there something I can do, maybe with the help of an appsettings.Development.json file? I've seen this answer; maybe a preprocessor directive is the way to go?

Thanks for any advice.


Solution

  • This is the way I've done it in my project:

    Install-Package Serilog.Sinks.File

    1. Create appSettings.development.json , appSettings.production.json with the copy of appSettings.json
    2. Remove serilog from appSettings.json
    3. In development replace "Seq" block with:
    {
            "Name": "File",
            "Args": {
              "path": "C:/Logs/MyConsoleApp/log-.log",
              "rollingInterval": "Day",
              "outputTemplate": "[{Timestamp:dd/MM HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
            }
    }
    

    Also Add using Serilog.Sinks.File:

    "Serilog": {
        "Using": [
          "Serilog.Sinks.File"
        ],
    

    If you want also Seq in addition to local file, don't replace its definition, just add to it.

    When you launch the project as development environment, appSettings.development.json is merged with appsettings.json . When you launch the project as production the same happens with appSettings.production.json and appSettings.json So appSettings.json should have the common config.