Skip to content

Commit

Permalink
Fall back to IDisposable in Log.CloseAndFlushAsync() when the target …
Browse files Browse the repository at this point in the history
…logger is not IAsyncDisposable
  • Loading branch information
nblumhardt committed Sep 27, 2024
1 parent 68881e1 commit b5085aa
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 4 deletions.
11 changes: 9 additions & 2 deletions src/Serilog/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,18 @@ public static void CloseAndFlush()
/// <summary>
/// Resets <see cref="Logger"/> to the default and disposes the original if possible
/// </summary>
public static ValueTask CloseAndFlushAsync()
public static async ValueTask CloseAndFlushAsync()
{
var logger = Interlocked.Exchange(ref _logger, Serilog.Core.Logger.None);

return (logger as IAsyncDisposable)?.DisposeAsync() ?? default;
if (logger is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync();
}
else
{
(logger as IDisposable)?.Dispose();
}
}
#endif

Expand Down
9 changes: 9 additions & 0 deletions test/Serilog.Tests/LogTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ public async Task CloseAndFlushAsyncDisposesTheLogger()
Assert.True(disposableLogger.IsDisposedAsync);
}

[Fact]
public async Task CloseAndFlushAsyncDisposesTheLoggerEvenWhenItIsNotAsyncDisposable()
{
var disposableLogger = new SyncDisposableLogger();
Log.Logger = disposableLogger;
await Log.CloseAndFlushAsync();
Assert.True(disposableLogger.IsDisposed);
}

[Fact]
public async Task CloseAndFlushAsyncResetsLoggerToSilentLogger()
{
Expand Down
2 changes: 0 additions & 2 deletions test/Serilog.Tests/Support/DisposableLogger.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#nullable enable

namespace Serilog.Tests.Support;

public class DisposableLogger : ILogger, IDisposable
Expand Down
19 changes: 19 additions & 0 deletions test/Serilog.Tests/Support/SyncDisposableLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#if FEATURE_ASYNCDISPOSABLE && FEATURE_DEFAULT_INTERFACE

namespace Serilog.Tests.Support;

public class SyncDisposableLogger: ILogger, IDisposable
{
public bool IsDisposed { get; private set; }

public void Write(LogEvent logEvent)
{
}

public void Dispose()
{
IsDisposed = true;
}
}

#endif

0 comments on commit b5085aa

Please sign in to comment.