From 3f07a9cfaf0ca0a15b24a079227c0ab0fb68a71e Mon Sep 17 00:00:00 2001 From: Rolf Kristensen Date: Tue, 21 Jan 2020 22:20:00 +0100 Subject: [PATCH] NLogLoggerFactory - Emulate Microsoft LoggerFactory by returning same ILogger instance (#380) --- .../Logging/NLogLogger.cs | 6 ++++++ .../Logging/NLogLoggerFactory.cs | 13 ++++++++++++- .../Logging/NLogLoggerFactoryTests.cs | 17 +++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/NLog.Extensions.Logging/Logging/NLogLogger.cs b/src/NLog.Extensions.Logging/Logging/NLogLogger.cs index 252fbc8e..3b726e04 100644 --- a/src/NLog.Extensions.Logging/Logging/NLogLogger.cs +++ b/src/NLog.Extensions.Logging/Logging/NLogLogger.cs @@ -402,6 +402,12 @@ private bool IsEnabled(LogLevel logLevel) return _logger.IsEnabled(logLevel); } + /// + public override string ToString() + { + return LoggerName; + } + /// /// Convert log level to NLog variant. /// diff --git a/src/NLog.Extensions.Logging/Logging/NLogLoggerFactory.cs b/src/NLog.Extensions.Logging/Logging/NLogLoggerFactory.cs index 0a671568..dd529ed8 100644 --- a/src/NLog.Extensions.Logging/Logging/NLogLoggerFactory.cs +++ b/src/NLog.Extensions.Logging/Logging/NLogLoggerFactory.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Microsoft.Extensions.Logging; using NLog.Common; @@ -9,6 +10,8 @@ namespace NLog.Extensions.Logging /// public class NLogLoggerFactory : ILoggerFactory { + private readonly Dictionary _loggers = new Dictionary(StringComparer.Ordinal); + private readonly NLogLoggerProvider _provider; /// @@ -66,7 +69,15 @@ protected virtual void Dispose(bool disposing) /// The . public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) { - return _provider.CreateLogger(categoryName); + lock (_loggers) + { + if (!_loggers.TryGetValue(categoryName, out var logger)) + { + logger = _provider.CreateLogger(categoryName); + _loggers[categoryName] = logger; + } + return logger; + } } /// diff --git a/test/NLog.Extensions.Logging.Tests/Logging/NLogLoggerFactoryTests.cs b/test/NLog.Extensions.Logging.Tests/Logging/NLogLoggerFactoryTests.cs index ce9e314b..f04551ce 100644 --- a/test/NLog.Extensions.Logging.Tests/Logging/NLogLoggerFactoryTests.cs +++ b/test/NLog.Extensions.Logging.Tests/Logging/NLogLoggerFactoryTests.cs @@ -56,5 +56,22 @@ public void AddProvider_StateUnderTest_ExpectedBehavior() // Assert Assert.Single(logFactory.Configuration.FindTargetByName("output").Logs); } + + [Fact] + public void CreateLogger_SameName_ReturnsSameInstanceTest() + { + // Arrange + var loggerFactory = new NLogLoggerFactory(); + string loggerName = "namespace.class1"; + + // Act + var result1 = loggerFactory.CreateLogger(loggerName); + var result2 = loggerFactory.CreateLogger(loggerName); + + // Assert + Assert.NotNull(result1); + Assert.Equal(loggerName, result1.ToString()); + Assert.Same(result1, result2); + } } }