1

Are there any options other than using preprocessor directives to enable / disable logging depending on the environment variable? I don't want sensitive data from the production environment to go into the logs. So it turns out that each environment will have its own configuration.

public class Service
{
    private readonly Serilog.ILogger logger;

    public Service(ILogger logger)
    {
        this.logger = logger;
    }

    public void DoSomething()
    {
#if DEBUG
        // if it's a development environment
        this.logger
            .ForContext("Debug data", data)
            .Information("something happened");
#endif
        // if it's a production environment
        this.logger.Information("something happened");
    }
}
arantar
  • 105
  • 1
  • 7
  • use configuration files to register a different ILogger for each environment, and handle inside each logger what information should be exposed – crankedrelic Jul 24 '20 at 15:52

2 Answers2

2

You can configure your Serilog pipeline based on conditions. You just need to decide how you're going to detect the environment your app is running on, and build the pipeline accordingly.

var configuration = new LoggerConfiguration()
    .WriteTo.Console();

if (condition)
{
    configuration.WriteTo.SomeOtherSink();
}

Log.Logger = configuration.CreateLogger();

Here are some more examples of configuring Serilog based on conditions:

You can also setup Serilog via a configuration file, and have separate configuration files per environment. Take a look at Serilog.Settings.Configuration if you want to use appsettings.json or Serilog.Settings.AppSettings if you want to use app.config.

C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
1

As of Serilog 2.9.0 you can use conditional sinks. By Using .WriteTo.Conditional you specify the condition that defines if the sink will be written to or not.

e.g.

bool enableConsoleLogging = (...)
bool enableFileLogging = (...)

var builder = new LoggerConfiguration()
    .Enrich.WithExceptionDetails()
    .Enrich.FromLogContext()
    .MinimumLevel.Warning()
    .WriteTo.Conditional(evt => enableConsoleLogging, wt => wt.Console())
    .WriteTo.Conditional(evt => enableFileLogging, wt => wt.File(...));

Log.Logger = builder.CreateLogger();
// ...
C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91