Skip to content

Commit

Permalink
NLogLoggerFactory - Optimize concurrency for CreateLogger (#692)
Browse files Browse the repository at this point in the history
  • Loading branch information
snakefoot authored Sep 13, 2023
1 parent 2beb830 commit e59c3cd
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/NLog.Extensions.Logging/Logging/NLogLoggerFactory.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using NLog.Common;

Expand All @@ -10,7 +10,7 @@ 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 ConcurrentDictionary<string, Microsoft.Extensions.Logging.ILogger> _loggers = new ConcurrentDictionary<string, Microsoft.Extensions.Logging.ILogger>(StringComparer.Ordinal);

private readonly NLogLoggerProvider _provider;

Expand Down Expand Up @@ -68,15 +68,18 @@ protected virtual void Dispose(bool disposing)
/// <returns>The <see cref="Microsoft.Extensions.Logging.ILogger" />.</returns>
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName)
{
lock (_loggers)
if (!_loggers.TryGetValue(categoryName, out var logger))
{
if (!_loggers.TryGetValue(categoryName, out var logger))
lock (_loggers)
{
logger = _provider.CreateLogger(categoryName);
_loggers[categoryName] = logger;
if (!_loggers.TryGetValue(categoryName, out logger))
{
logger = _provider.CreateLogger(categoryName);
_loggers[categoryName] = logger;
}
}
return logger;
}
return logger;
}

/// <summary>
Expand Down

0 comments on commit e59c3cd

Please sign in to comment.