#1920·serilog

Proposal: Add support for TimeProvider

Author: 0xcedCreated Jun 19, 2023Updated Oct 4, 2024
Labelsenhancement

Is your feature request related to a problem? Please describe. The current Serilog implementation uses DateTimeOffset.Now for setting the Timestamp property of log events. This might complicate unit testing as the log event timestamps are not predictable.

Describe the solution you'd like .NET 8 is introducing time abstraction with a new TimeProvider class (also available down-level with the new Microsoft.Bcl.TimeProvider NuGet package). It could be used to have full control over how the log event timestamps are created.

Describe alternatives you've considered The alternative is to not use the new TimeProvider and keep the status quo. Authors of Serilog add-ons will have to find workarounds in their testing code when it comes to the predictability of the log event timestamps.

Additional context I have already prototyped two possible solutions to address this issue:

  1. Make TimeProvider available only when targeting .NET 8: https://github.com/0xced/serilog/tree/TimeProvider-ConditionalCompilation
  2. Make TimeProvider available on all target platforms by taking a dependency on the Microsoft.Bcl.TimeProvider NuGet package: https://github.com/0xced/serilog/tree/TimeProvider-Microsoft.Bcl-Dependency

The shape of the API I have experimented with is to add a new overload to the CreateLogger method. Other possibilities are also conceivable, such as a new LoggerTimeProviderConfiguration fluent builder.

csharp
namespace Serilog;

public class LoggerConfiguration
{
    public Logger CreateLogger() => CreateLogger(TimeProvider.System);

    public Logger CreateLogger(TimeProvider timeProvider)
    {
    }
}

What are your thoughts about this?