Add LoggerColorBehavior (#40221)
authorMaryam Ariyan <maryam.ariyan@microsoft.com>
Wed, 5 Aug 2020 00:25:03 +0000 (17:25 -0700)
committerGitHub <noreply@github.com>
Wed, 5 Aug 2020 00:25:03 +0000 (17:25 -0700)
src/libraries/Microsoft.Extensions.Logging.Console/ref/Microsoft.Extensions.Logging.Console.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerOptions.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProvider.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/LoggerColorBehavior.cs [new file with mode: 0644]
src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatterOptions.cs
src/libraries/Microsoft.Extensions.Logging.Console/tests/ConsoleFormatterTests.cs
src/libraries/Microsoft.Extensions.Logging.Console/tests/ConsoleLoggerExtensionsTests.cs
src/libraries/Microsoft.Extensions.Logging.Console/tests/ConsoleLoggerTest.cs
src/libraries/Microsoft.Extensions.Logging.Console/tests/SimpleConsoleFormatterTests.cs

index c7ed2ea..0ffa786 100644 (file)
@@ -50,7 +50,7 @@ namespace Microsoft.Extensions.Logging.Console
     public partial class ConsoleLoggerOptions
     {
         public ConsoleLoggerOptions() { }
-        [System.ObsoleteAttribute("ConsoleLoggerOptions.DisableColors has been deprecated. Please use SimpleConsoleFormatterOptions.DisableColors instead.", false)]
+        [System.ObsoleteAttribute("ConsoleLoggerOptions.DisableColors has been deprecated. Please use SimpleConsoleFormatterOptions.ColorBehavior instead.", false)]
         public bool DisableColors { get { throw null; } set { } }
         [System.ObsoleteAttribute("ConsoleLoggerOptions.Format has been deprecated. Please use ConsoleLoggerOptions.FormatterName instead.", false)]
         public Microsoft.Extensions.Logging.Console.ConsoleLoggerFormat Format { get { throw null; } set { } }
@@ -77,10 +77,16 @@ namespace Microsoft.Extensions.Logging.Console
         public JsonConsoleFormatterOptions() { }
         public System.Text.Json.JsonWriterOptions JsonWriterOptions { get { throw null; } set { } }
     }
+    public enum LoggerColorBehavior
+    {
+        Default = 0,
+        Enabled = 1,
+        Disabled = 2,
+    }
     public partial class SimpleConsoleFormatterOptions : Microsoft.Extensions.Logging.Console.ConsoleFormatterOptions
     {
         public SimpleConsoleFormatterOptions() { }
-        public bool DisableColors { get { throw null; } set { } }
+        public Microsoft.Extensions.Logging.Console.LoggerColorBehavior ColorBehavior { get { throw null; } set { } }
         public bool SingleLine { get { throw null; } set { } }
     }
 }
index cda6f89..5951124 100644 (file)
@@ -13,7 +13,7 @@ namespace Microsoft.Extensions.Logging.Console
         /// <summary>
         /// Disables colors when <see langword="true" />.
         /// </summary>
-        [System.ObsoleteAttribute("ConsoleLoggerOptions.DisableColors has been deprecated. Please use SimpleConsoleFormatterOptions.DisableColors instead.", false)]
+        [System.ObsoleteAttribute("ConsoleLoggerOptions.DisableColors has been deprecated. Please use SimpleConsoleFormatterOptions.ColorBehavior instead.", false)]
         public bool DisableColors { get; set; }
 
 #pragma warning disable CS0618
index 4c5c596..d5a2252 100644 (file)
@@ -153,7 +153,7 @@ namespace Microsoft.Extensions.Logging.Console
             {
                 defaultFormatter.FormatterOptions = new SimpleConsoleFormatterOptions()
                 {
-                    DisableColors = deprecatedFromOptions.DisableColors,
+                    ColorBehavior = deprecatedFromOptions.DisableColors ? LoggerColorBehavior.Disabled : LoggerColorBehavior.Enabled,
                     IncludeScopes = deprecatedFromOptions.IncludeScopes,
                     TimestampFormat = deprecatedFromOptions.TimestampFormat,
                     UseUtcTimestamp = deprecatedFromOptions.UseUtcTimestamp,
diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/LoggerColorBehavior.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/LoggerColorBehavior.cs
new file mode 100644 (file)
index 0000000..c38ec19
--- /dev/null
@@ -0,0 +1,27 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+namespace Microsoft.Extensions.Logging.Console
+{
+    /// <summary>
+    /// Determines when to use color when logging messages.
+    /// </summary>
+    public enum LoggerColorBehavior
+    {
+        /// <summary>
+        /// Use the default color behavior, enabling color except when the console output is redirected.
+        /// </summary>
+        /// <remarks>
+        /// Enables color except when the console output is redirected.
+        /// </remarks>
+        Default,
+        /// <summary>
+        /// Enable color for logging
+        /// </summary>
+        Enabled,
+        /// <summary>
+        /// Disable color for logging
+        /// </summary>
+        Disabled,
+    }
+}
index f5b0571..bc702ca 100644 (file)
@@ -147,7 +147,9 @@ namespace Microsoft.Extensions.Logging.Console
 
         private ConsoleColors GetLogLevelConsoleColors(LogLevel logLevel)
         {
-            if (FormatterOptions.DisableColors)
+            bool disableColors = (FormatterOptions.ColorBehavior == LoggerColorBehavior.Disabled) ||
+                (FormatterOptions.ColorBehavior == LoggerColorBehavior.Default && System.Console.IsOutputRedirected);
+            if (disableColors)
             {
                 return new ConsoleColors(null, null);
             }
index 9ee51c1..44aab1e 100644 (file)
@@ -11,9 +11,9 @@ namespace Microsoft.Extensions.Logging.Console
         public SimpleConsoleFormatterOptions() { }
 
         /// <summary>
-        /// Disables colors when <see langword="true" />.
+        /// Determines when to use color when logging messages.
         /// </summary>
-        public bool DisableColors { get; set; }
+        public LoggerColorBehavior ColorBehavior { get; set; }
 
         /// <summary>
         /// When <see langword="false" />, the entire message gets logged in a single line.
index 580a745..78e1709 100644 (file)
@@ -126,7 +126,7 @@ namespace Microsoft.Extensions.Logging.Console.Test
             // Arrange
             var t = SetUp(
                 new ConsoleLoggerOptions { FormatterName = formatterName },
-                new SimpleConsoleFormatterOptions { TimestampFormat = "yyyy-MM-ddTHH:mm:sszz ", UseUtcTimestamp = false },
+                new SimpleConsoleFormatterOptions { TimestampFormat = "yyyy-MM-ddTHH:mm:sszz ", UseUtcTimestamp = false, ColorBehavior = LoggerColorBehavior.Enabled },
                 new ConsoleFormatterOptions { TimestampFormat = "yyyy-MM-ddTHH:mm:sszz ", UseUtcTimestamp = false },
                 new JsonConsoleFormatterOptions {
                     TimestampFormat = "yyyy-MM-ddTHH:mm:sszz ",
index a5f02fe..739978b 100644 (file)
@@ -157,7 +157,7 @@ namespace Microsoft.Extensions.Logging.Test
         public void AddSimpleConsole_ChangeProperties_IsReadFromLoggingConfiguration()
         {
             var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] {
-                new KeyValuePair<string, string>("Console:FormatterOptions:DisableColors", "true"),
+                new KeyValuePair<string, string>("Console:FormatterOptions:ColorBehavior", "Disabled"),
                 new KeyValuePair<string, string>("Console:FormatterOptions:SingleLine", "true"),
                 new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "),
                 new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"),
@@ -176,7 +176,7 @@ namespace Microsoft.Extensions.Logging.Test
             var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category");
             Assert.Equal(ConsoleFormatterNames.Simple, logger.Options.FormatterName);
             var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter);
-            Assert.True(formatter.FormatterOptions.DisableColors);
+            Assert.Equal(LoggerColorBehavior.Disabled, formatter.FormatterOptions.ColorBehavior);
             Assert.True(formatter.FormatterOptions.SingleLine);
             Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat);
             Assert.True(formatter.FormatterOptions.UseUtcTimestamp);
@@ -424,7 +424,7 @@ namespace Microsoft.Extensions.Logging.Test
             Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat);  // ignore FormatterOptions, using deprecated one
             Assert.False(formatter.FormatterOptions.UseUtcTimestamp);               // not set anywhere, defaulted to false
             Assert.False(formatter.FormatterOptions.IncludeScopes);                 // setup using lambda wins over config
-            Assert.True(formatter.FormatterOptions.DisableColors);                  // setup using lambda
+            Assert.Equal(LoggerColorBehavior.Disabled, formatter.FormatterOptions.ColorBehavior);                  // setup using lambda
         }
 
         [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
@@ -467,7 +467,7 @@ namespace Microsoft.Extensions.Logging.Test
             Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat);     // ignore deprecated, using FormatterOptions instead
             Assert.False(formatter.FormatterOptions.UseUtcTimestamp);               // not set anywhere, defaulted to false
             Assert.True(formatter.FormatterOptions.IncludeScopes);                  // ignore deprecated set in lambda use FormatterOptions instead
-            Assert.False(formatter.FormatterOptions.DisableColors);                 // ignore deprecated set in lambda, defaulted to false
+            Assert.Equal(LoggerColorBehavior.Default, formatter.FormatterOptions.ColorBehavior);                 // ignore deprecated set in lambda, defaulted to false
         }
 
         [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
index 9f6a99f..ebe9985 100644 (file)
@@ -86,7 +86,8 @@ namespace Microsoft.Extensions.Logging.Console.Test
                 Assert.Equal(formatter.FormatterOptions.IncludeScopes, logger.Options.IncludeScopes);
                 Assert.Equal(formatter.FormatterOptions.UseUtcTimestamp, logger.Options.UseUtcTimestamp);
                 Assert.Equal(formatter.FormatterOptions.TimestampFormat, logger.Options.TimestampFormat);
-                Assert.Equal(formatter.FormatterOptions.DisableColors, logger.Options.DisableColors);   
+                Assert.Equal(formatter.FormatterOptions.ColorBehavior, 
+                    logger.Options.DisableColors ? LoggerColorBehavior.Disabled : LoggerColorBehavior.Enabled);   
             }
             else
             {
@@ -102,7 +103,8 @@ namespace Microsoft.Extensions.Logging.Console.Test
             // kept for deprecated apis:
             if (formatter is SimpleConsoleFormatter defaultFormatter)
             {
-                defaultFormatter.FormatterOptions.DisableColors = deprecatedFromOptions.DisableColors;
+                defaultFormatter.FormatterOptions.ColorBehavior = deprecatedFromOptions.DisableColors ? 
+                    LoggerColorBehavior.Disabled : LoggerColorBehavior.Enabled;
                 defaultFormatter.FormatterOptions.IncludeScopes = deprecatedFromOptions.IncludeScopes;
                 defaultFormatter.FormatterOptions.TimestampFormat = deprecatedFromOptions.TimestampFormat;
                 defaultFormatter.FormatterOptions.UseUtcTimestamp = deprecatedFromOptions.UseUtcTimestamp;
index 9a54c78..3bb1fa4 100644 (file)
@@ -9,13 +9,16 @@ namespace Microsoft.Extensions.Logging.Console.Test
 {
     public class SimpleConsoleFormatterTests : ConsoleFormatterTests
     {
-        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
-        public void Log_WritingScopes_LogsWithCorrectColors()
+        [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
+        [InlineData(LoggerColorBehavior.Default)]
+        [InlineData(LoggerColorBehavior.Enabled)]
+        [InlineData(LoggerColorBehavior.Disabled)]
+        public void Log_WritingScopes_LogsWithCorrectColorsWhenColorEnabled(LoggerColorBehavior colorBehavior)
         {
             // Arrange
             var t = SetUp(
                 new ConsoleLoggerOptions { FormatterName = ConsoleFormatterNames.Simple },
-                new SimpleConsoleFormatterOptions { IncludeScopes = true }
+                new SimpleConsoleFormatterOptions { IncludeScopes = true, ColorBehavior = colorBehavior }
                 );
             var logger = t.Logger;
             var sink = t.Sink;
@@ -29,13 +32,25 @@ namespace Microsoft.Extensions.Logging.Console.Test
             }
 
             // Assert
-            Assert.Equal(2, sink.Writes.Count);
-            var write = sink.Writes[0];
-            Assert.Equal(ConsoleColor.Black, write.BackgroundColor);
-            Assert.Equal(ConsoleColor.DarkGreen, write.ForegroundColor);
-            write = sink.Writes[1];
-            Assert.Equal(TestConsole.DefaultBackgroundColor, write.BackgroundColor);
-            Assert.Equal(TestConsole.DefaultForegroundColor, write.ForegroundColor);
+            switch (colorBehavior)
+            {
+                case LoggerColorBehavior.Enabled:
+                    Assert.Equal(2, sink.Writes.Count);
+                    var write = sink.Writes[0];
+                    Assert.Equal(ConsoleColor.Black, write.BackgroundColor);
+                    Assert.Equal(ConsoleColor.DarkGreen, write.ForegroundColor);
+                    write = sink.Writes[1];
+                    Assert.Equal(TestConsole.DefaultBackgroundColor, write.BackgroundColor);
+                    Assert.Equal(TestConsole.DefaultForegroundColor, write.ForegroundColor);
+                    break;
+                case LoggerColorBehavior.Default:
+                case LoggerColorBehavior.Disabled:
+                    Assert.Equal(1, sink.Writes.Count);
+                    write = sink.Writes[0];
+                    Assert.Equal(TestConsole.DefaultBackgroundColor, write.BackgroundColor);
+                    Assert.Equal(TestConsole.DefaultForegroundColor, write.ForegroundColor);
+                    break;
+            }
         }
 
         [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
@@ -44,7 +59,7 @@ namespace Microsoft.Extensions.Logging.Console.Test
             // Arrange
             var t = SetUp(
                 new ConsoleLoggerOptions { FormatterName = ConsoleFormatterNames.Simple },
-                new SimpleConsoleFormatterOptions { IncludeScopes = true }
+                new SimpleConsoleFormatterOptions { IncludeScopes = true, ColorBehavior = LoggerColorBehavior.Enabled }
             );
             var logger = t.Logger;
             var sink = t.Sink;
@@ -68,7 +83,7 @@ namespace Microsoft.Extensions.Logging.Console.Test
             // Arrange
             var t = SetUp(
                 new ConsoleLoggerOptions { FormatterName = ConsoleFormatterNames.Simple },
-                new SimpleConsoleFormatterOptions { SingleLine = true }
+                new SimpleConsoleFormatterOptions { SingleLine = true, ColorBehavior = LoggerColorBehavior.Enabled }
             );
             var logger = (ILogger)t.Logger;
             var sink = t.Sink;
@@ -99,7 +114,7 @@ namespace Microsoft.Extensions.Logging.Console.Test
             // Arrange
             var t = SetUp(
                 new ConsoleLoggerOptions { FormatterName = ConsoleFormatterNames.Simple },
-                new SimpleConsoleFormatterOptions { SingleLine = true }
+                new SimpleConsoleFormatterOptions { SingleLine = true, ColorBehavior = LoggerColorBehavior.Enabled }
             );
             var logger = (ILogger)t.Logger;
             var sink = t.Sink;