using System.Text;
using NLog;
using NLog.Targets;
using LogLevel = NLog.LogLevel;
namespace OliverBooth.Logging;
///
/// Represents an NLog target which supports colorful output to stdout.
///
internal sealed class ColorfulConsoleTarget : TargetWithLayout
{
///
/// Initializes a new instance of the class.
///
/// The name of the log target.
public ColorfulConsoleTarget(string name)
{
Name = name;
}
///
protected override void Write(LogEventInfo logEvent)
{
var message = new StringBuilder();
message.Append(Layout.Render(logEvent));
if (logEvent.Level == LogLevel.Warn)
Console.ForegroundColor = ConsoleColor.Yellow;
else if (logEvent.Level == LogLevel.Error || logEvent.Level == LogLevel.Fatal)
Console.ForegroundColor = ConsoleColor.Red;
if (logEvent.Exception is { } exception)
message.Append($": {exception}");
Console.WriteLine(message);
Console.ResetColor();
}
}