-
Notifications
You must be signed in to change notification settings - Fork 2
/
SingleLineConsoleLogger.cs
199 lines (174 loc) · 6.14 KB
/
SingleLineConsoleLogger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace NetBricks;
public static class AddSingleLineConsoleLoggerConfiguration
{
public static void AddSingleLineConsoleLogger(this IServiceCollection services, bool logParams = true)
{
// log the logger variables
if (logParams)
{
Console.WriteLine($"LOG_LEVEL = \"{Config.LOG_LEVEL}\"");
Console.WriteLine($"DISABLE_COLORS = \"{Config.DISABLE_COLORS}\"");
}
// add the logger
services
.AddLogging(configure =>
{
services.TryAddSingleton<ILoggerProvider, SingleLineConsoleLoggerProvider>();
})
.Configure<LoggerFilterOptions>(options =>
{
options.MinLevel = Config.LOG_LEVEL;
});
}
}
public class SingleLineConsoleLoggerProvider : ILoggerProvider
{
private ConcurrentDictionary<string, SingleLineConsoleLogger> Loggers = new ConcurrentDictionary<string, SingleLineConsoleLogger>();
public ILogger CreateLogger(string categoryName)
{
return Loggers.GetOrAdd(categoryName, name => new SingleLineConsoleLogger(name, Config.DISABLE_COLORS));
}
public void Dispose()
{
foreach (var logger in Loggers)
{
logger.Value.Shutdown();
}
Loggers.Clear();
}
}
public class SingleLineConsoleLogger : ILogger
{
public SingleLineConsoleLogger(string name, bool disableColors)
{
this.Name = name;
this.DisableColors = disableColors;
Dispatcher = Task.Run(() =>
{
while (!QueueTakeCts.IsCancellationRequested)
{
try
{
Console.WriteLine(Queue.Take(QueueTakeCts.Token));
}
catch (OperationCanceledException)
{
// let the loop end
}
}
IsShutdown.Set();
});
}
private string Name { get; }
private bool DisableColors { get; }
private BlockingCollection<string> Queue { get; set; } = new BlockingCollection<string>();
private CancellationTokenSource QueueTakeCts { get; set; } = new CancellationTokenSource();
private Task Dispatcher { get; set; }
private ManualResetEventSlim IsShutdown { get; set; } = new ManualResetEventSlim(false);
public void Shutdown()
{
QueueTakeCts.Cancel();
IsShutdown.Wait(5000);
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel != LogLevel.None;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
if (formatter == null)
{
throw new ArgumentNullException(nameof(formatter));
}
// write the message
var message = formatter(state, exception);
if (!string.IsNullOrEmpty(message))
{
// write the message
var sb = new StringBuilder();
var logLevelColors = GetLogLevelConsoleColors(logLevel);
if (!DisableColors && logLevelColors.Foreground != null) sb.Append(logLevelColors.Foreground);
if (!DisableColors && logLevelColors.Background != null) sb.Append(logLevelColors.Background);
var logLevelString = GetLogLevelString(logLevel);
sb.Append(logLevelString);
if (!DisableColors) sb.Append("\u001b[0m"); // reset
sb.Append($" {DateTime.UtcNow.ToString()} [src:{Name}] ");
sb.Append(message);
Queue.Add(sb.ToString());
}
// write the exception
if (exception != null)
{
Console.WriteLine(exception.ToString());
}
}
private static string GetLogLevelString(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
return "trce";
case LogLevel.Debug:
return "dbug";
case LogLevel.Information:
return "info";
case LogLevel.Warning:
return "warn";
case LogLevel.Error:
return "fail";
case LogLevel.Critical:
return "crit";
default:
throw new ArgumentOutOfRangeException(nameof(logLevel));
}
}
private ConsoleColors GetLogLevelConsoleColors(LogLevel logLevel)
{
if (DisableColors) return new ConsoleColors(null, null);
// We must explicitly set the background color if we are setting the foreground color,
// since just setting one can look bad on the users console.
switch (logLevel)
{
case LogLevel.Critical:
return new ConsoleColors("\u001b[37m", "\u001b[41m"); // white on red
case LogLevel.Error:
return new ConsoleColors("\u001b[30m", "\u001b[41m"); // black on red
case LogLevel.Warning:
return new ConsoleColors("\u001b[33m", "\u001b[40m"); // yellow on black
case LogLevel.Information:
return new ConsoleColors("\u001b[32m", "\u001b[40m"); // green on black
case LogLevel.Debug:
return new ConsoleColors("\u001b[37m", "\u001b[40m"); // white on black
case LogLevel.Trace:
return new ConsoleColors("\u001b[37m", "\u001b[40m"); // white on black
default:
return new ConsoleColors(null, null);
}
}
private readonly struct ConsoleColors
{
public ConsoleColors(string foreground, string background)
{
Foreground = foreground;
Background = background;
}
public string Foreground { get; }
public string Background { get; }
}
}