Skip to content

Commit

Permalink
Merge pull request #67 from nblumhardt/suppress-execution-context-flow
Browse files Browse the repository at this point in the history
Prevent capturing of the sink-creation-time `ExecutionContext` by the batching loop/batched sink
  • Loading branch information
nblumhardt authored Feb 2, 2024
2 parents 180f5e7 + 010449c commit 773fdb6
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ public PeriodicBatchingSink(IBatchedLogEventSink batchedSink, PeriodicBatchingSi
_waitForShutdownSignal = Task.Delay(Timeout.InfiniteTimeSpan, _shutdownSignal.Token)
.ContinueWith(e => e.Exception, TaskContinuationOptions.OnlyOnFaulted);

_runLoop = Task.Run(LoopAsync);
// The conditional here is no longer required in .NET 8+ (dotnet/runtime#82912)
using (ExecutionContext.IsFlowSuppressed() ? (IDisposable?)null : ExecutionContext.SuppressFlow())
{
_runLoop = Task.Run(LoopAsync);
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,27 @@ public void WhenAnEventIsEnqueuedItIsWrittenToABatchOnDisposeWhileRunning()
Assert.True(bs.IsDisposed);
Assert.False(bs.WasCalledAfterDisposal);
}

[Fact]
public void ExecutionContextDoesNotFlowToBatchedSink()
{
var local = new AsyncLocal<int>
{
Value = 5
};

var observed = 17;
var bs = new CallbackBatchedSink(_ =>
{
observed = local.Value;
return Task.CompletedTask;
});

var pbs = new PeriodicBatchingSink(bs, new());
var evt = Some.InformationEvent();
pbs.Emit(evt);
pbs.Dispose();

Assert.Equal(default(int), observed);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Serilog.Events;

namespace Serilog.Sinks.PeriodicBatching.Tests.Support;

class CallbackBatchedSink(Func<IEnumerable<LogEvent>, Task> callback) : IBatchedLogEventSink
{
public Task EmitBatchAsync(IEnumerable<LogEvent> batch)
{
return callback(batch);
}

public Task OnEmptyBatchAsync()
{
return Task.CompletedTask;
}
}

0 comments on commit 773fdb6

Please sign in to comment.