Skip to content

Commit

Permalink
serilog#773 - clone and re-import LogContext.
Browse files Browse the repository at this point in the history
  • Loading branch information
nblumhardt committed May 27, 2017
1 parent 36f8429 commit 6190ca8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 16 deletions.
31 changes: 15 additions & 16 deletions src/Serilog/Context/LogContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,17 @@ public static IDisposable PushProperties(params ILogEventEnricher[] properties)
return Push(properties);
}

/// <summary>
/// Obtain an enricher that represents the current contents of the <see cref="LogContext"/>. This
/// can be pushed back onto the context in a different location/thread when required.
/// </summary>
/// <returns>An enricher that represents the current contents of the <see cref="LogContext"/>.</returns>
public static ILogEventEnricher Clone()
{
var stack = GetOrCreateEnricherStack();
return new SafeAggregateEnricher(stack);
}

static ImmutableStack<ILogEventEnricher> GetOrCreateEnricherStack()
{
var enrichers = Enrichers;
Expand Down Expand Up @@ -181,14 +192,8 @@ public void Dispose()

static ImmutableStack<ILogEventEnricher> Enrichers
{
get
{
return Data.Value;
}
set
{
Data.Value = value;
}
get => Data.Value;
set => Data.Value = value;
}

#elif REMOTING
Expand All @@ -211,14 +216,8 @@ static ImmutableStack<ILogEventEnricher> Enrichers

static ImmutableStack<ILogEventEnricher> Enrichers
{
get
{
return Data;
}
set
{
Data = value;
}
get => Data;
set => Data = value;
}
#endif
}
Expand Down
24 changes: 24 additions & 0 deletions test/Serilog.Tests/Context/LogContextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#endif
using System.Threading;
using System.Threading.Tasks;
using Serilog.Core;

namespace Serilog.Tests.Context
{
Expand Down Expand Up @@ -46,6 +47,29 @@ public void PushedPropertiesAreAvailableToLoggers()
}
}

[Fact]
public void LogContextCanBeCloned()
{
LogEvent lastEvent = null;

var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();

ILogEventEnricher clonedContext;
using (LogContext.PushProperty("A", 1))
{
clonedContext = LogContext.Clone();
}

using (LogContext.Push(clonedContext))
{
log.Write(Some.InformationEvent());
Assert.Equal(1, lastEvent.Properties["A"].LiteralValue());
}
}

[Fact]
public void MoreNestedPropertiesOverrideLessNestedOnes()
{
Expand Down

0 comments on commit 6190ca8

Please sign in to comment.