JSON Console Logger not requiring scopes to implement IReadOnlyCollection (#48453)
authordaveMueller <muellerdavid4@gmail.com>
Fri, 19 Feb 2021 03:35:00 +0000 (04:35 +0100)
committerGitHub <noreply@github.com>
Fri, 19 Feb 2021 03:35:00 +0000 (19:35 -0800)
src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs
src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/JsonConsoleFormatterTests.cs

index c08038c..793294c 100644 (file)
@@ -109,7 +109,7 @@ namespace Microsoft.Extensions.Logging.Console
                 writer.WriteStartArray("Scopes");
                 scopeProvider.ForEachScope((scope, state) =>
                 {
-                    if (scope is IReadOnlyCollection<KeyValuePair<string, object>> scopes)
+                    if (scope is IEnumerable<KeyValuePair<string, object>> scopes)
                     {
                         state.WriteStartObject();
                         state.WriteString("Message", scope.ToString());
index af9ef06..e4df53a 100644 (file)
@@ -342,6 +342,35 @@ namespace Microsoft.Extensions.Logging.Console.Test
             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<string, object>("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<object, string> SpecialCaseValues
         {
             get