Skip to content

Async disposal on .NET 6 or later #262

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

Merged
merged 4 commits into from
Nov 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Serilog.Core;
using Serilog.Events;
Expand All @@ -14,13 +15,19 @@ namespace Serilog.Extensions.Logging;
/// </summary>
[ProviderAlias("Serilog")]
public class SerilogLoggerProvider : ILoggerProvider, ILogEventEnricher, ISupportExternalScope
#if NET6_0_OR_GREATER
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Serilog projects define constants for each conditional feature centrally in the CSPROJ, e.g.:

https://github.com/serilog/serilog/blob/dev/src/Serilog/Serilog.csproj

Could we define FEATURE_ASYNCDISPOSABLE and use it in place of the version constraints in the code?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uh, dooh. Sorry about that. I had noticed that the Serilog core code base used such flags, but forgot to check this code. I will address.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have defined FEATURE_ASYNCDISPOSABLE now

, IAsyncDisposable
#endif
{
internal const string OriginalFormatPropertyName = "{OriginalFormat}";
internal const string ScopePropertyName = "Scope";

// May be null; if it is, Log.Logger will be lazily used
readonly ILogger? _logger;
readonly Action? _dispose;
#if NET6_0_OR_GREATER
readonly Func<ValueTask>? _disposeAsync;
#endif
private IExternalScopeProvider? _externalScopeProvider;

/// <summary>
Expand All @@ -36,9 +43,25 @@ public SerilogLoggerProvider(ILogger? logger = null, bool dispose = false)
if (dispose)
{
if (logger != null)
{
_dispose = () => (logger as IDisposable)?.Dispose();
#if NET6_0_OR_GREATER
_disposeAsync = () =>
{
// Dispose via IAsyncDisposable if possible, otherwise fall back to IDisposable
if (logger is IAsyncDisposable asyncDisposable) return asyncDisposable.DisposeAsync();
else (logger as IDisposable)?.Dispose();
return default;
};
#endif
}
else
{
_dispose = Log.CloseAndFlush;
#if NET6_0_OR_GREATER
_disposeAsync = Log.CloseAndFlushAsync;
#endif
}
}
}

Expand Down Expand Up @@ -113,4 +136,12 @@ public void Dispose()
{
_dispose?.Invoke();
}

#if NET6_0_OR_GREATER
/// <inheritdoc />
public ValueTask DisposeAsync()
{
return _disposeAsync?.Invoke() ?? default;
}
#endif
}
72 changes: 72 additions & 0 deletions test/Serilog.Extensions.Logging.Tests/DisposeTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog.Core;
using Serilog.Events;
using Xunit;

namespace Serilog.Extensions.Logging.Tests;

public class DisposeTests
{
private readonly DisposableSink _sink;
private readonly Logger _serilogLogger;

public DisposeTests()
{
_sink = new DisposableSink();
_serilogLogger = new LoggerConfiguration()
.WriteTo.Sink(_sink)
.CreateLogger();
}

[Fact]
public void AddSerilog_must_dispose_the_provider_when_dispose_is_true()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Serilog codebases use PascalCaseForTestNames(); shortening this to something like DisposesProviderWhenDisposeIsTrue() would help make the scheme work.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I will address!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Naming changed

{
var services = new ServiceCollection()
.AddLogging(builder => builder.AddSerilog(logger: _serilogLogger, dispose: true))
.BuildServiceProvider();

// Get a logger so that we ensure SerilogLoggerProvider is created
var logger = services.GetRequiredService<ILogger<DisposeTests>>();
logger.LogInformation("Hello, world!");

services.Dispose();
Assert.True(_sink.DisposeCalled);
Assert.False(_sink.DisposeAsyncCalled);
}

#if NET8_0_OR_GREATER
[Fact]
public async Task AddSerilog_must_async_dispose_the_provider_when_dispose_is_true()
{
var services = new ServiceCollection()
.AddLogging(builder => builder.AddSerilog(logger: _serilogLogger, dispose: true))
.BuildServiceProvider();

// Get a logger so that we ensure SerilogLoggerProvider is created
var logger = services.GetRequiredService<ILogger<DisposeTests>>();
logger.LogInformation("Hello, world!");

await services.DisposeAsync();
Assert.False(_sink.DisposeCalled);
Assert.True(_sink.DisposeAsyncCalled);
}
#endif

private sealed class DisposableSink : ILogEventSink, IDisposable, IAsyncDisposable
{
public bool DisposeAsyncCalled { get; private set; }
public bool DisposeCalled { get; private set; }

public void Dispose() => DisposeCalled = true;
public ValueTask DisposeAsync()
{
DisposeAsyncCalled = true;
return default;
}

public void Emit(LogEvent logEvent)
{
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog.Extensions.Logging.Tests.Support;
using Xunit;

namespace Serilog.Extensions.Logging.Tests;

public class SerilogLoggingBuilderExtensionsTests
{
[Fact]
public void AddSerilog_must_register_a_ILoggerProvider()
{
var services = new ServiceCollection()
.AddLogging(builder => { builder.AddSerilog(); })
.BuildServiceProvider();

var loggerProviders = services.GetServices<ILoggerProvider>();
Assert.Contains(loggerProviders, provider => provider is SerilogLoggerProvider);
}

[Fact]
public void AddSerilog_must_register_a_ILoggerProvider_that_forwards_logs_to_static_Serilog_Logger()
{
var sink = new SerilogSink();
Log.Logger = new LoggerConfiguration()
.WriteTo.Sink(sink)
.CreateLogger();

var services = new ServiceCollection()
.AddLogging(builder => { builder.AddSerilog(); })
.BuildServiceProvider();

var logger = services.GetRequiredService<ILogger<SerilogLoggingBuilderExtensionsTests>>();
logger.LogInformation("Hello, world!");

Assert.Single(sink.Writes);
}

[Fact]
public void AddSerilog_must_register_a_ILoggerProvider_that_forwards_logs_to_provided_logger()
{
var sink = new SerilogSink();
var serilogLogger = new LoggerConfiguration()
.WriteTo.Sink(sink)
.CreateLogger();

var services = new ServiceCollection()
.AddLogging(builder => { builder.AddSerilog(logger: serilogLogger); })
.BuildServiceProvider();

var logger = services.GetRequiredService<ILogger<SerilogLoggingBuilderExtensionsTests>>();
logger.LogInformation("Hello, world!");

Assert.Single(sink.Writes);
}
}