|
| 1 | +using System; |
| 2 | +using Serilog; |
| 3 | +using Serilog.Configuration; |
| 4 | +using Serilog.Core; |
| 5 | +using Serilog.Events; |
| 6 | +using Serilog.Formatting; |
| 7 | +using Serilog.Formatting.Display; |
| 8 | + |
| 9 | +namespace NitroxModel.Logger |
| 10 | +{ |
| 11 | + public class ColoredConsoleSink : ILogEventSink |
| 12 | + { |
| 13 | + private readonly ConsoleColor defaultBackground = Console.BackgroundColor; |
| 14 | + private readonly ConsoleColor defaultForeground = Console.ForegroundColor; |
| 15 | + |
| 16 | + private readonly ITextFormatter formatter; |
| 17 | + |
| 18 | + public ColoredConsoleSink(ITextFormatter formatter) |
| 19 | + { |
| 20 | + this.formatter = formatter; |
| 21 | + } |
| 22 | + |
| 23 | + public void Emit(LogEvent logEvent) |
| 24 | + { |
| 25 | + (Console.ForegroundColor, Console.BackgroundColor) = logEvent.Level switch |
| 26 | + { |
| 27 | + LogEventLevel.Verbose => (ConsoleColor.DarkGray, defaultBackground), |
| 28 | + LogEventLevel.Debug => (ConsoleColor.DarkGray, defaultBackground), |
| 29 | + LogEventLevel.Information => (ConsoleColor.Gray, defaultBackground), |
| 30 | + LogEventLevel.Warning => (ConsoleColor.Yellow, defaultBackground), |
| 31 | + LogEventLevel.Error => (ConsoleColor.Red, defaultBackground), |
| 32 | + LogEventLevel.Fatal => (ConsoleColor.Red, ConsoleColor.Yellow), |
| 33 | + _ => (defaultForeground, defaultBackground) |
| 34 | + }; |
| 35 | + |
| 36 | + formatter.Format(logEvent, Console.Out); |
| 37 | + Console.Out.Flush(); |
| 38 | + |
| 39 | + Console.ForegroundColor = defaultForeground; |
| 40 | + Console.BackgroundColor = defaultBackground; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public static class ColoredConsoleSinkExtensions |
| 45 | + { |
| 46 | + public static LoggerConfiguration ColoredConsole( |
| 47 | + this LoggerSinkConfiguration loggerConfiguration, |
| 48 | + LogEventLevel minimumLevel = LogEventLevel.Verbose, |
| 49 | + string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", |
| 50 | + IFormatProvider formatProvider = null) |
| 51 | + { |
| 52 | + return loggerConfiguration.Sink(new ColoredConsoleSink(new MessageTemplateTextFormatter(outputTemplate, formatProvider)), minimumLevel); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments