Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ namespace Microsoft.DotNet.Scaffolding.Core.Logging;
/// </summary>
internal class CleanConsoleFormatter : ConsoleFormatter
{
private const string BrightRedColor = "\x1B[1;31m";
private const string BrightYellowColor = "\x1B[1;33m";
private const string ResetColor = "\x1B[0m";

/// <summary>
/// Initializes a new instance of the <see cref="CleanConsoleFormatter"/> class.
/// </summary>
Expand All @@ -31,10 +35,33 @@ public override void Write<TState>(in LogEntry<TState> 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);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense to maintain consistency with AnsiConsole

}

textWriter.WriteLine(message);

if (message is not null)
if (colorCode is not null)
{
textWriter.WriteLine(message);
textWriter.Write(ResetColor);
}
}
}