using System;
using System.Collections.Generic;
namespace ExtremelySimpleLogger {
///
/// A that writes log output to .
///
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 object locker = new object();
///
/// 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 .
///
/// 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.locker) {
var color = this.GetColor(level);
if (color.HasValue)
Console.ForegroundColor = color.Value;
Console.WriteLine(s);
if (color.HasValue)
Console.ResetColor();
}
}
}
}