using System; using System.Collections.Generic; using System.IO; namespace ExtremelySimpleLogger { /// /// A that writes log output to or . /// This class is a variation of the . /// public class ConsoleSink : Sink { /// /// The that each is displayed with using this console sink. /// To edit and query this collection, you can also use and . /// public readonly Dictionary ConsoleColors = new Dictionary { {LogLevel.Warn, ConsoleColor.DarkYellow}, {LogLevel.Error, ConsoleColor.DarkRed}, {LogLevel.Fatal, ConsoleColor.DarkRed} }; private readonly TextWriter console; private readonly bool useAnsiCodes; /// /// Creates a new console sink with the given settings. /// /// Whether to log to instead of . /// Whether to wrap log output text in ANSI escape codes using instead of using the and . This may work better on some terminals. public ConsoleSink(bool error = false, bool useAnsiCodes = false) { this.console = error ? Console.Error : Console.Out; this.useAnsiCodes = useAnsiCodes; } /// /// Sets the that text with the given should be displayed with. /// To set the default color for the log level, simply pass a with no value to . /// /// The log level to set the color for /// The color to use, or a with no value to clear the current color /// This instance, for chaining public virtual ConsoleSink SetColor(LogLevel level, ConsoleColor? color) { if (color.HasValue) { this.ConsoleColors[level] = color.Value; } else { this.ConsoleColors.Remove(level); } return this; } /// /// Returns the that text with the given is displayed with. /// If text is displayed with the default console color, a without a value is returned. /// /// The log level whose color to query /// The console color that text with the log level is displayed with, or a with no value if no color is set public virtual ConsoleColor? GetColor(LogLevel level) { if (this.ConsoleColors.TryGetValue(level, out var color)) return color; return null; } /// /// Logs the given message, which has already been formatted using or . /// /// The logger that the message was passed to /// The importance level of this message /// The message to log protected override void Log(Logger logger, LogLevel level, string s) { lock (this.console) { var color = this.GetColor(level); if (color.HasValue) { if (this.useAnsiCodes) { s = s.WrapAnsiCode(color.Value); } else { Console.ForegroundColor = color.Value; } } this.console.WriteLine(s); if (color.HasValue && !this.useAnsiCodes) Console.ResetColor(); } } } }