diff --git a/src/Serilog/LoggerConfiguration.cs b/src/Serilog/LoggerConfiguration.cs index 5b89e2782..70c2f5c03 100644 --- a/src/Serilog/LoggerConfiguration.cs +++ b/src/Serilog/LoggerConfiguration.cs @@ -38,6 +38,7 @@ public class LoggerConfiguration LogEventLevel _minimumLevel = LogEventLevel.Information; LoggingLevelSwitch _levelSwitch; int _maximumDestructuringDepth = 10; + bool _loggerCreated; /// /// Configures the sinks that log events will be emitted to. @@ -124,6 +125,10 @@ public LoggerSettingsConfiguration ReadFrom /// disposed. public ILogger CreateLogger() { + if (_loggerCreated) + throw new InvalidOperationException($"CreateLogger was previously called and can only be called once."); + _loggerCreated = true; + if (!_logEventSinks.Any()) return new SilentLogger(); diff --git a/test/Serilog.Tests/LoggerConfigurationTests.cs b/test/Serilog.Tests/LoggerConfigurationTests.cs index 5a354457e..094269bc4 100644 --- a/test/Serilog.Tests/LoggerConfigurationTests.cs +++ b/test/Serilog.Tests/LoggerConfigurationTests.cs @@ -26,6 +26,14 @@ public void Dispose() } } + [Fact] + public void CreateLoggerThrowsIfCalledMoreThanOnce() + { + var loggerConfiguration = new LoggerConfiguration(); + loggerConfiguration.CreateLogger(); + Assert.Throws(() => loggerConfiguration.CreateLogger()); + } + [Fact] public void DisposableSinksAreDisposedAlongWithRootLogger() {