From 5b363abc271c7da9565e859b24da92a8195719f1 Mon Sep 17 00:00:00 2001 From: Phil Henning Date: Wed, 3 Dec 2025 16:29:03 -0500 Subject: [PATCH] Color console output based on LogLevel Uses the same approach as .NET's built-in console formatters by writing ANSI escape codes to the TextWriter --- .../Logging/CleanConsoleFormatter.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/dotnet-scaffolding/Microsoft.DotNet.Scaffolding.Core/Logging/CleanConsoleFormatter.cs b/src/dotnet-scaffolding/Microsoft.DotNet.Scaffolding.Core/Logging/CleanConsoleFormatter.cs index 0e583392c..1c23f95fd 100644 --- a/src/dotnet-scaffolding/Microsoft.DotNet.Scaffolding.Core/Logging/CleanConsoleFormatter.cs +++ b/src/dotnet-scaffolding/Microsoft.DotNet.Scaffolding.Core/Logging/CleanConsoleFormatter.cs @@ -12,6 +12,10 @@ namespace Microsoft.DotNet.Scaffolding.Core.Logging; /// internal class CleanConsoleFormatter : ConsoleFormatter { + private const string BrightRedColor = "\x1B[1;31m"; + private const string BrightYellowColor = "\x1B[1;33m"; + private const string ResetColor = "\x1B[0m"; + /// /// Initializes a new instance of the class. /// @@ -31,10 +35,33 @@ public override void Write(in LogEntry logEntry, IExternalScopeP { // Format the log message using the provided formatter, ignoring log level and category. string? message = logEntry.Formatter?.Invoke(logEntry.State, logEntry.Exception); + if (message is null) + { + return; + } + + // Apply console color using ANSI escape codes (only if output is not redirected). + // Uses a similar approach as .NET's built-in console formatters. + // See: https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Logging.Console/src/TextWriterExtensions.cs + string? colorCode = !Console.IsOutputRedirected + ? logEntry.LogLevel switch + { + LogLevel.Error or LogLevel.Critical => BrightRedColor, + LogLevel.Warning => BrightYellowColor, + _ => null + } + : null; + + if (colorCode is not null) + { + textWriter.Write(colorCode); + } + + textWriter.WriteLine(message); - if (message is not null) + if (colorCode is not null) { - textWriter.WriteLine(message); + textWriter.Write(ResetColor); } } }