Skip to content
New issue

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

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

Already on GitHub? # to your account

Fix contention in LoggerFactory.CreateLogger #87904

Merged
merged 1 commit into from
Jun 22, 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
20 changes: 12 additions & 8 deletions src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -14,7 +15,7 @@ namespace Microsoft.Extensions.Logging
/// </summary>
public class LoggerFactory : ILoggerFactory
{
private readonly Dictionary<string, Logger> _loggers = new Dictionary<string, Logger>(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, Logger> _loggers = new ConcurrentDictionary<string, Logger>(StringComparer.Ordinal);
private readonly List<ProviderRegistration> _providerRegistrations = new List<ProviderRegistration>();
private readonly object _sync = new object();
private volatile bool _disposed;
Expand Down Expand Up @@ -138,19 +139,22 @@ public ILogger CreateLogger(string categoryName)
throw new ObjectDisposedException(nameof(LoggerFactory));
}

lock (_sync)
if (!_loggers.TryGetValue(categoryName, out Logger? logger))
{
if (!_loggers.TryGetValue(categoryName, out Logger? logger))
lock (_sync)
{
logger = new Logger(categoryName, CreateLoggers(categoryName));
if (!_loggers.TryGetValue(categoryName, out logger))
{
logger = new Logger(categoryName, CreateLoggers(categoryName));

(logger.MessageLoggers, logger.ScopeLoggers) = ApplyFilters(logger.Loggers);
(logger.MessageLoggers, logger.ScopeLoggers) = ApplyFilters(logger.Loggers);

_loggers[categoryName] = logger;
_loggers[categoryName] = logger;
}
}

return logger;
}

return logger;
}

/// <summary>
Expand Down