From 01fa69d714d177d11d45db76c33bc3cae7451333 Mon Sep 17 00:00:00 2001 From: Dave Glick Date: Sat, 7 Nov 2015 20:29:45 -0500 Subject: [PATCH] LoggerConfiguration.CreateLogger() now throws if called more than once, resolves #561 --- src/Serilog/LoggerConfiguration.cs | 5 +++++ test/Serilog.Tests/LoggerConfigurationTests.cs | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/src/Serilog/LoggerConfiguration.cs b/src/Serilog/LoggerConfiguration.cs index 0f662e80a..a8795eb26 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 1178436da..92ba973fb 100644 --- a/test/Serilog.Tests/LoggerConfigurationTests.cs +++ b/test/Serilog.Tests/LoggerConfigurationTests.cs @@ -25,6 +25,14 @@ public void Dispose() } } + [Test] + public void CreateLoggerThrowsIfCalledMoreThanOnce() + { + var loggerConfiguration = new LoggerConfiguration(); + loggerConfiguration.CreateLogger(); + Assert.Throws(() => loggerConfiguration.CreateLogger()); + } + [Test] public void DisposableSinksAreDisposedAlongWithRootLogger() {