I would like to configure Serilog in the program code with predefined values, because we often have the same logging requirements. So that the default values can be changed, I want to configure Serilog with environment variables and command line parameters via the IConfigurationBuilder.
My problem is that I can't delete anything from the config object. That means if someone adds a sink that is already configured by default, it will exist twice.
Can I prevent this somehow? Do you have any ideas for me how to prevent duplicate entries in the resulting configuration?
Here is some example code, maybe for clarification:
using Serilog;
using Serilog.Events;
using System;
using Microsoft.Extensions.Configuration;
using Serilog.Exceptions;
namespace example.Logging;
public static class LoggingConfigurator
{
public static LoggerConfiguration CreateLoggerConfiguration(
IConfiguration configuration,
bool useStandardConfig = true,
Func<LoggerConfiguration, LoggerConfiguration> configure = null)
{
var loggerConfiguration = new LoggerConfiguration();
if (useStandardConfig)
{
// standard configuration
loggerConfiguration.MinimumLevel.Override("microsoft", LogEventLevel.Warning);
loggerConfiguration.Enrich.FromLogContext();
loggerConfiguration.Enrich.WithExceptionDetails();
loggerConfiguration.WriteTo.Async(
a =>
{
a.Debug();
a.Console();
}
);
}
if (configure is not null)
{
loggerConfiguration = configure(loggerConfiguration);
}
loggerConfiguration.ReadFrom.Configuration(configuration);
return loggerConfiguration;
}
}