allow using ANSI escape sequences for the console sink

This commit is contained in:
Ell 2023-12-01 13:17:46 +01:00
parent 034497201e
commit 8e5bd41a47
3 changed files with 58 additions and 5 deletions

View file

@ -19,13 +19,16 @@ namespace ExtremelySimpleLogger {
{LogLevel.Fatal, ConsoleColor.DarkRed} {LogLevel.Fatal, ConsoleColor.DarkRed}
}; };
private readonly TextWriter console; private readonly TextWriter console;
private readonly bool useAnsiCodes;
/// <summary> /// <summary>
/// Creates a new console sink with the given settings. /// Creates a new console sink with the given settings.
/// </summary> /// </summary>
/// <param name="error">Whether to log to <see cref="Console.Error"/> instead of <see cref="Console.Out"/>.</param> /// <param name="error">Whether to log to <see cref="Console.Error"/> instead of <see cref="Console.Out"/>.</param>
public ConsoleSink(bool error = false) { /// <param name="useAnsiCodes">Whether to wrap log output text in ANSI escape codes using <see cref="Extensions.WrapAnsiCode"/> instead of using the <see cref="Console.ForegroundColor"/> and <see cref="Console.ResetColor"/>. This may work better on some terminals.</param>
public ConsoleSink(bool error = false, bool useAnsiCodes = false) {
this.console = error ? Console.Error : Console.Out; this.console = error ? Console.Error : Console.Out;
this.useAnsiCodes = useAnsiCodes;
} }
/// <summary> /// <summary>
@ -65,10 +68,15 @@ namespace ExtremelySimpleLogger {
protected override void Log(Logger logger, LogLevel level, string s) { protected override void Log(Logger logger, LogLevel level, string s) {
lock (this.console) { lock (this.console) {
var color = this.GetColor(level); var color = this.GetColor(level);
if (color.HasValue) if (color.HasValue) {
if (this.useAnsiCodes) {
s = s.WrapAnsiCode(color.Value);
} else {
Console.ForegroundColor = color.Value; Console.ForegroundColor = color.Value;
}
}
this.console.WriteLine(s); this.console.WriteLine(s);
if (color.HasValue) if (color.HasValue && !this.useAnsiCodes)
Console.ResetColor(); Console.ResetColor();
} }
} }

View file

@ -0,0 +1,45 @@
using System;
using System.Linq;
namespace ExtremelySimpleLogger {
/// <summary>
/// A set of extension methods for logging-related activities, like converting <see cref="ConsoleColor"/> to ANSI color codes.
/// </summary>
public static class Extensions {
private static readonly int[] AnsiCodes = new[] {
ConsoleColor.Black, ConsoleColor.DarkRed, ConsoleColor.DarkGreen, ConsoleColor.DarkYellow,
ConsoleColor.DarkBlue, ConsoleColor.DarkMagenta, ConsoleColor.DarkCyan, ConsoleColor.Gray,
ConsoleColor.DarkGray, ConsoleColor.Red, ConsoleColor.Green, ConsoleColor.Yellow,
ConsoleColor.Blue, ConsoleColor.Magenta, ConsoleColor.Cyan, ConsoleColor.White
}.Select((s, i) => (int) s).ToArray();
/// <summary>
/// Converts the given <see cref="ConsoleColor"/> to its ANSI escape sequence representation. If the supplied <paramref name="color"/> is <see langword="null"/>, the reset escape sequence for the given color type will be returned.
/// </summary>
/// <param name="color">The color. If <see langword="null"/>, the reset escape sequence for the given color type will be returned.</param>
/// <param name="background">Whether to return a background color. If this is <see langword="false"/>, a foreground color is returned instead.</param>
/// <returns>The ANSI escape sequence representation of the given <paramref name="color"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">If the <paramref name="color"/> is not in defined range.</exception>
public static string ToAnsiCode(this ConsoleColor? color, bool background = false) {
if (color.HasValue) {
if (color < 0 || (int) color >= Extensions.AnsiCodes.Length)
throw new ArgumentOutOfRangeException(nameof(color), color, null);
return $"\x1B[{(background ? 48 : 38)};5;{Extensions.AnsiCodes[(int) color]}m";
}
return $"\x1B[{(background ? 49 : 39)}m";
}
/// <summary>
/// Wraps the given string in the ANSI escape sequence representation of the given <paramref name="color"/> and the appropriate reset escape sequence using <see cref="ToAnsiCode"/>.
/// </summary>
/// <param name="s">The string to wrap.</param>
/// <param name="color">The color.</param>
/// <param name="background">Whether to use <paramref name="color"/> as a background color. If this is <see langword="false"/>, a foreground color is used instead.</param>
/// <returns>The given string, wrapped in ANSI color codes.</returns>
public static string WrapAnsiCode(this string s, ConsoleColor color, bool background = false) {
return Extensions.ToAnsiCode(color, background) + s + Extensions.ToAnsiCode(null, background);
}
}
}

View file

@ -12,7 +12,7 @@ namespace Sample {
var sinks = new List<Sink> { var sinks = new List<Sink> {
new FileSink("Log.txt", true), new FileSink("Log.txt", true),
// We only want to log messages with a higher importance in the console // We only want to log messages with a higher importance in the console
new ConsoleSink {MinimumLevel = LogLevel.Info}, new ConsoleSink() {MinimumLevel = LogLevel.Info},
// we allow a total of 5 files in our directory sink before old ones start being deleted // we allow a total of 5 files in our directory sink before old ones start being deleted
new DirectorySink("AllLogs", 5) new DirectorySink("AllLogs", 5)
}; };