Skip to content

Commit

Permalink
NLogLoggerFactory - Emulate Microsoft LoggerFactory by returning same…
Browse files Browse the repository at this point in the history
… ILogger instance (#380)
  • Loading branch information
snakefoot authored and 304NotModified committed Jan 21, 2020
1 parent ab088e2 commit 3f07a9c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/NLog.Extensions.Logging/Logging/NLogLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,12 @@ private bool IsEnabled(LogLevel logLevel)
return _logger.IsEnabled(logLevel);
}

/// <inheritdoc />
public override string ToString()
{
return LoggerName;
}

/// <summary>
/// Convert log level to NLog variant.
/// </summary>
Expand Down
13 changes: 12 additions & 1 deletion src/NLog.Extensions.Logging/Logging/NLogLoggerFactory.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using NLog.Common;

Expand All @@ -9,6 +10,8 @@ namespace NLog.Extensions.Logging
/// </summary>
public class NLogLoggerFactory : ILoggerFactory
{
private readonly Dictionary<string, Microsoft.Extensions.Logging.ILogger> _loggers = new Dictionary<string, Microsoft.Extensions.Logging.ILogger>(StringComparer.Ordinal);

private readonly NLogLoggerProvider _provider;

/// <summary>
Expand Down Expand Up @@ -66,7 +69,15 @@ protected virtual void Dispose(bool disposing)
/// <returns>The <see cref="T:Microsoft.Extensions.Logging.ILogger" />.</returns>
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;
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,22 @@ public void AddProvider_StateUnderTest_ExpectedBehavior()
// Assert
Assert.Single(logFactory.Configuration.FindTargetByName<Targets.MemoryTarget>("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);
}
}
}

0 comments on commit 3f07a9c

Please sign in to comment.