From 6190ca819f3f3a63faa282170f48e23ebf82d37c Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Sun, 28 May 2017 08:36:01 +1000 Subject: [PATCH] #773 - clone and re-import LogContext. --- src/Serilog/Context/LogContext.cs | 31 +++++++++---------- test/Serilog.Tests/Context/LogContextTests.cs | 24 ++++++++++++++ 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/src/Serilog/Context/LogContext.cs b/src/Serilog/Context/LogContext.cs index 0b9723ad9..accfe9da0 100644 --- a/src/Serilog/Context/LogContext.cs +++ b/src/Serilog/Context/LogContext.cs @@ -139,6 +139,17 @@ public static IDisposable PushProperties(params ILogEventEnricher[] properties) return Push(properties); } + /// + /// Obtain an enricher that represents the current contents of the . This + /// can be pushed back onto the context in a different location/thread when required. + /// + /// An enricher that represents the current contents of the . + public static ILogEventEnricher Clone() + { + var stack = GetOrCreateEnricherStack(); + return new SafeAggregateEnricher(stack); + } + static ImmutableStack GetOrCreateEnricherStack() { var enrichers = Enrichers; @@ -181,14 +192,8 @@ public void Dispose() static ImmutableStack Enrichers { - get - { - return Data.Value; - } - set - { - Data.Value = value; - } + get => Data.Value; + set => Data.Value = value; } #elif REMOTING @@ -211,14 +216,8 @@ static ImmutableStack Enrichers static ImmutableStack Enrichers { - get - { - return Data; - } - set - { - Data = value; - } + get => Data; + set => Data = value; } #endif } diff --git a/test/Serilog.Tests/Context/LogContextTests.cs b/test/Serilog.Tests/Context/LogContextTests.cs index f2c184e29..a6bf641ac 100644 --- a/test/Serilog.Tests/Context/LogContextTests.cs +++ b/test/Serilog.Tests/Context/LogContextTests.cs @@ -12,6 +12,7 @@ #endif using System.Threading; using System.Threading.Tasks; +using Serilog.Core; namespace Serilog.Tests.Context { @@ -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() {