Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NLogLoggerFactory - Optimize concurrency for CreateLogger #692

Merged
merged 1 commit into from
Sep 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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