Skip to content

Commit

Permalink
fix(logging): Replace locks with concurrent dict [ci]
Browse files Browse the repository at this point in the history
Simplified the scopes in dummy logger to just use a concurrent dictionary
ignoring the value side.

Fixes the invalid lock code and correct analyser error raised.
  • Loading branch information
bmazzarol committed Mar 11, 2023
1 parent 26cc9c6 commit 58550c2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 19 deletions.
26 changes: 9 additions & 17 deletions BunsenBurner.Logging/DummyLogger.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Logging;

Expand All @@ -13,7 +14,7 @@ public sealed record DummyLogger<T> : ILogger<T>, IEnumerable<LogMessage>, IDisp
private readonly string _ownerClassName;
private readonly LogMessageStore _store;
private readonly Sink? _sink;
private IEnumerable<Scope> _scopes = Enumerable.Empty<Scope>();
private readonly ConcurrentDictionary<Scope, byte> _scopes = new();

internal DummyLogger(LogMessageStore store, string ownerClassName, Sink? sink)
{
Expand All @@ -37,7 +38,7 @@ public void Log<TState>(
eventId,
exception,
formatter(state, exception),
_scopes.Select(x => x.State)
_scopes.Keys.Select(x => x.State)
);
_store.Log(message);
_sink?.Write(message);
Expand All @@ -49,22 +50,15 @@ public void Log<TState>(
/// <inheritdoc />
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
lock (_scopes)
{
var scope = new Scope(state, this);
_scopes = _scopes.Append(scope);
return scope;
}
var scope = new Scope(state, this);
_scopes.AddOrUpdate(scope, _ => byte.MinValue, (_, b) => b);
return scope;
}

private sealed record Scope(object State, DummyLogger<T> Parent) : IDisposable
{
[ExcludeFromCodeCoverage]
public void Dispose()
{
lock (Parent._scopes)
Parent._scopes = Parent._scopes.Where(x => x != this);
}
public void Dispose() => Parent._scopes.TryRemove(this, out _);
}

/// <inheritdoc />
Expand All @@ -76,11 +70,9 @@ public void Dispose()
/// <inheritdoc />
public void Dispose()
{
foreach (var scope in _scopes)
{
foreach (var scope in _scopes.Keys)
scope.Dispose();
}
_scopes = Enumerable.Empty<Scope>();
_scopes.Clear();
}
}

Expand Down
4 changes: 2 additions & 2 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
"header-case": [1, "always", "sentence-case"],
"header-max-length": [2, "always", 100],
"subject-case": [0, 'never'],
"subject-max-length": [2, "always", 100],
"scope-enum": _ => [
2,
"always",
Expand Down

0 comments on commit 58550c2

Please sign in to comment.