-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSingleLineConsoleLogger.cs
More file actions
252 lines (223 loc) · 8.34 KB
/
SingleLineConsoleLogger.cs
File metadata and controls
252 lines (223 loc) · 8.34 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace NetBricks;
internal class SingleLineConsoleLoggerProvider : ILoggerProvider
{
public SingleLineConsoleLoggerProvider(SingleLineConsoleLoggerOptions options)
{
this.SingleLineConsoleLoggerOptions = options;
}
private SingleLineConsoleLoggerOptions SingleLineConsoleLoggerOptions { get; }
private ConcurrentDictionary<string, SingleLineConsoleLogger> Loggers = new ConcurrentDictionary<string, SingleLineConsoleLogger>();
private bool disposed;
private readonly object disposeLock = new object();
public ILogger CreateLogger(string categoryName)
{
return Loggers.GetOrAdd(categoryName, name => new SingleLineConsoleLogger(name, SingleLineConsoleLoggerOptions));
}
protected virtual void Dispose(bool disposing)
{
lock (this.disposeLock)
{
if (!this.disposed)
{
if (disposing)
{
foreach (var logger in Loggers)
{
logger.Value.Dispose();
}
Loggers.Clear();
}
// free unmanaged resources (unmanaged objects) and override finalizer
// set large fields to null
this.disposed = true;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
internal class SingleLineConsoleLogger : ILogger, IDisposable
{
internal SingleLineConsoleLogger(string name, SingleLineConsoleLoggerOptions options)
{
this.Name = name;
this.Options = options;
// create an unbounded channel for the log messages
LogChannel = System.Threading.Channels.Channel.CreateUnbounded<string>(new UnboundedChannelOptions
{
SingleReader = true, // only one reader will be reading from the channel
AllowSynchronousContinuations = false // process continuations asynchronously
});
// start the dispatcher task
Dispatcher = Task.Run(async () =>
{
try
{
await foreach (var message in LogChannel.Reader.ReadAllAsync(CancellationToken))
{
Console.WriteLine(message);
}
IsShutdown.Set();
}
catch (Exception ex)
{
Console.WriteLine($"Error in SingleLineConsoleLogger Dispatcher: {ex}");
}
});
}
private string Name { get; }
private SingleLineConsoleLoggerOptions Options { get; }
private Channel<string> LogChannel { get; }
private CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource();
private CancellationToken CancellationToken => CancellationTokenSource.Token;
private Task Dispatcher { get; }
private ManualResetEventSlim IsShutdown { get; } = new ManualResetEventSlim(false);
private bool disposedValue;
private readonly Lazy<bool> channelErrorReported = new Lazy<bool>(() =>
{
Console.WriteLine("SingleLineConsoleLogger: Channel is full, writing to console directly.");
return true;
}, LazyThreadSafetyMode.ExecutionAndPublication);
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 (this.Options.LOG_WITH_COLORS && logLevelColors.Foreground is not null) sb.Append(logLevelColors.Foreground);
if (this.Options.LOG_WITH_COLORS && logLevelColors.Background is not null) sb.Append(logLevelColors.Background);
var logLevelString = GetLogLevelString(logLevel);
sb.Append(logLevelString);
if (this.Options.LOG_WITH_COLORS) sb.Append("\u001b[0m"); // reset
sb.Append($" {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss.fff} [src:{Name}] ");
sb.Append(message);
// the channel should only be full if the system is out of memory
if (!LogChannel.Writer.TryWrite(sb.ToString()))
{
_ = this.channelErrorReported.Value;
Console.WriteLine(message);
}
}
// write the exception
if (exception != null)
{
// For exceptions, we want to ensure they appear in the log
// We could also put this in the channel, but direct console output
// ensures it appears immediately even if the channel is backed up
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 (!this.Options.LOG_WITH_COLORS) 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; }
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if (disposing)
{
try
{
LogChannel.Writer.Complete();
CancellationTokenSource.Cancel();
IsShutdown.Wait(5000);
}
finally
{
CancellationTokenSource.Dispose();
IsShutdown.Dispose();
}
}
// free unmanaged resources (unmanaged objects) and override finalizer
// set large fields to null
this.disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return null;
}
}