From fdd77cc8994cd2d6b0520fdc7e9233dd05fdb7d9 Mon Sep 17 00:00:00 2001 From: Rolf Kristensen Date: Tue, 29 Sep 2020 01:17:21 +0200 Subject: [PATCH] NLogBeginScopeParser - Reduce allocation for BeginScope with message template --- .../Logging/NLogBeginScopeParser.cs | 24 ++++++++++++++++++- .../CustomBeginScopeTest.cs | 21 ++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/NLog.Extensions.Logging/Logging/NLogBeginScopeParser.cs b/src/NLog.Extensions.Logging/Logging/NLogBeginScopeParser.cs index 54e9beaa..8dd0db6c 100644 --- a/src/NLog.Extensions.Logging/Logging/NLogBeginScopeParser.cs +++ b/src/NLog.Extensions.Logging/Logging/NLogBeginScopeParser.cs @@ -95,6 +95,28 @@ public static IDisposable CaptureScopeProperties(IReadOnlyList 0 && NLogLogger.OriginalFormatPropertyName.Equals(scopePropertyList[scopePropertyList.Count - 1].Key)) + { + scopePropertyList = ExcludeOriginalFormatProperty(scopePropertyList); + } + + return CreateScopeProperties(scopeObject, scopePropertyList); + } + + private static IReadOnlyList> ExcludeOriginalFormatProperty(IReadOnlyList> scopePropertyList) + { + if (scopePropertyList.Count == 2 && !NLogLogger.OriginalFormatPropertyName.Equals(scopePropertyList[0].Key)) + { + scopePropertyList = new[] { scopePropertyList[0] }; + } + else if (scopePropertyList.Count <= 2) + { +#if NET451 + scopePropertyList = new KeyValuePair[0]; +#else + scopePropertyList = Array.Empty>(); +#endif + } + else { var propertyList = new List>(scopePropertyList.Count - 1); for (var i = 0; i < scopePropertyList.Count; ++i) @@ -110,7 +132,7 @@ public static IDisposable CaptureScopeProperties(IReadOnlyList(); + var target = new Targets.MemoryTarget { Layout = "${message} ${mdlc:Planet}. Welcome to the ${mdlc:Galaxy}" }; + ConfigureNLog(target); + var scopeString = runner.SayHiToEarth().Result; + Assert.Single(target.Logs); + Assert.Equal("Hi Earth. Welcome to the Milky Way", target.Logs[0]); + } + [Fact] public void TestNonSerializableSayNothing() { @@ -82,6 +93,16 @@ public async Task SayHi() } } + public async Task SayHiToEarth() + { + using (var scopeState = _logger.BeginScope("{Planet} in {Galaxy}", "Earth", "Milky Way")) + { + await Task.Yield(); + _logger.LogInformation("Hi"); + return scopeState.ToString(); + } + } + public async Task SayNothing() { using (var scopeState = _logger.BeginScope(new Dictionary()))