From 8a0bcab37302e66dbf0ab55adb795b3ab5f7c3ee 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 | 22 +++++++++++++++++ 2 files changed, 45 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]); + // Assert.Equal("Earth People", scopeString); <-- Bug https://github.com/aspnet/Logging/issues/893 + } + [Fact] public void TestNonSerializableSayNothing() { @@ -82,6 +94,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()))