From ed2e7490b3179f423128223ce42cb197de7a8a99 Mon Sep 17 00:00:00 2001 From: daveMueller Date: Fri, 19 Feb 2021 04:35:00 +0100 Subject: [PATCH] JSON Console Logger not requiring scopes to implement IReadOnlyCollection (#48453) --- .../src/JsonConsoleFormatter.cs | 2 +- .../JsonConsoleFormatterTests.cs | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs index c08038c5df9..793294ce2a1 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs @@ -109,7 +109,7 @@ private void WriteScopeInformation(Utf8JsonWriter writer, IExternalScopeProvider writer.WriteStartArray("Scopes"); scopeProvider.ForEachScope((scope, state) => { - if (scope is IReadOnlyCollection> scopes) + if (scope is IEnumerable> scopes) { state.WriteStartObject(); state.WriteString("Message", scope.ToString()); diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/JsonConsoleFormatterTests.cs b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/JsonConsoleFormatterTests.cs index af9ef06edd5..e4df53adbc4 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/JsonConsoleFormatterTests.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/JsonConsoleFormatterTests.cs @@ -342,6 +342,35 @@ public void Log_StateAndScopeContainsNullValue_SerializesNull() Assert.Contains("\"LogKey\":null", message); } + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] + public void Log_ScopeIsIEnumerable_SerializesKeyValuePair() + { + // Arrange + var t = SetUp( + new ConsoleLoggerOptions { FormatterName = ConsoleFormatterNames.Json }, + simpleOptions: null, + systemdOptions: null, + jsonOptions: new JsonConsoleFormatterOptions + { + JsonWriterOptions = new JsonWriterOptions() { Indented = false }, + IncludeScopes = true + } + ); + var logger = (ILogger)t.Logger; + var sink = t.Sink; + + // Act + using (logger.BeginScope(new[] { 2 }.Select(x => new KeyValuePair("Value", x)))) + { + logger.LogInformation("{LogEntryNumber}", 1); + } + + // Assert + string message = sink.Writes[0].Message; + Assert.Contains("\"Message\":\"System.Linq.Enumerable", message); + Assert.Contains("\"Value\":" + 2, message); + } + public static TheoryData SpecialCaseValues { get -- GitLab