-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogger.cs
More file actions
376 lines (320 loc) · 12.4 KB
/
Logger.cs
File metadata and controls
376 lines (320 loc) · 12.4 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using DSharpPlus;
using DSharpPlus.Exceptions;
using System.Threading;
using System.IO;
using Microsoft.Extensions.Hosting.Systemd;
using Tmds.Systemd;
namespace RoleBoi;
internal class LoggerProvider : ILoggerProvider
{
public void Dispose() { /* nothing to dispose */ }
public ILogger CreateLogger(string categoryName)
{
return new Logger(categoryName);
}
}
public class Logger(string logCategory) : ILogger
{
public static Logger Instance { get; } = new Logger(RoleBoi.APPLICATION_NAME);
private static LogLevel minimumLogLevel = LogLevel.Trace;
private static readonly Lock consoleLock = new();
private static readonly Lock fileLock = new();
private bool IsSingleton => logCategory == RoleBoi.APPLICATION_NAME;
private static List<string> startupCache = [];
private static TextWriter logFileWriter = null;
private static readonly EventId botEventId = new EventId(420, "BOT");
internal static void SetLogLevel(LogLevel level)
{
minimumLogLevel = level;
}
internal static void Debug(string message, Exception exception = null)
{
Instance.Log(LogLevel.Debug, botEventId, exception, message);
}
internal static void Log(string message, Exception exception = null)
{
Instance.Log(LogLevel.Information, botEventId, exception, message);
}
internal static void Warn(string message, Exception exception = null)
{
Instance.Log(LogLevel.Warning, botEventId, exception, message);
}
internal static void Error(string message, Exception exception = null)
{
Instance.Log(LogLevel.Error, botEventId, exception, message);
}
internal static void Fatal(string message, Exception exception = null)
{
Instance.Log(LogLevel.Critical, botEventId, exception, message);
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= minimumLogLevel && logLevel != LogLevel.None;
}
public IDisposable BeginScope<TState>(TState state) where TState : notnull => default;
private static ConsoleColor GetLogLevelColour(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => ConsoleColor.White,
LogLevel.Debug => ConsoleColor.DarkGray,
LogLevel.Information => ConsoleColor.DarkBlue,
LogLevel.Warning => ConsoleColor.Yellow,
LogLevel.Error => ConsoleColor.Red,
_ => ConsoleColor.White
};
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
string message = formatter(state, exception);
// Ratelimit messages are usually warnings, but they are unimportant in this case so downgrade them to debug.
if (message.StartsWith("Hit Discord ratelimit on route ") && logLevel == LogLevel.Warning)
{
logLevel = LogLevel.Debug;
}
// The bot will handle NotFoundExceptions on its own, downgrade to debug
else if (exception is NotFoundException && eventId == LoggerEvents.RestError)
{
logLevel = LogLevel.Debug;
}
// Remove HTTP Client spam
if (logCategory.StartsWith("System.Net.Http.HttpClient"))
{
return;
}
LogToFile(logLevel, message, exception);
LogToConsoleOrSystemd(logLevel, message, exception);
}
private void LogToConsoleOrSystemd(LogLevel logLevel, string message, Exception exception)
{
if (!IsEnabled(logLevel))
{
return;
}
if (SystemdHelpers.IsSystemdService())
{
SystemdLog(logLevel, exception, message);
}
else
{
ConsoleLog(logLevel, exception, message);
}
}
private void SystemdLog(LogLevel logLevel, Exception exception, string message)
{
string logLevelTag = logLevel switch
{
LogLevel.Trace => "[Trace] ",
LogLevel.Debug => "[Debug] ",
LogLevel.Information => " [Info] ",
LogLevel.Warning => " [Warn] ",
LogLevel.Error => "[Error] ",
LogLevel.Critical => " [Crit] ",
_ => " [None] ",
};
LogFlags priority = logLevel switch
{
LogLevel.Trace => LogFlags.Debug,
LogLevel.Debug => LogFlags.Debug,
LogLevel.Information => LogFlags.Information,
LogLevel.Warning => LogFlags.Warning,
LogLevel.Error => LogFlags.Error,
LogLevel.Critical => LogFlags.Critical,
_ => LogFlags.Information
};
string logMessage = (IsSingleton ? "[BOT] " : "[API] ") + logLevelTag + message;
if (exception != null)
{
logMessage += "\n" + GetExceptionString(exception, 0);
}
JournalMessage msg = Journal.GetMessage().Append(JournalFieldName.Message, logMessage);
if (Journal.IsAvailable)
{
Journal.Log(priority, msg);
}
else
{
Console.WriteLine(logMessage);
}
}
private void ConsoleLog(LogLevel logLevel, Exception exception, string message)
{
string[] logLevelParts = logLevel switch
{
LogLevel.Trace => ["[", "Trace", "] "],
LogLevel.Debug => ["[", "Debug", "] "],
LogLevel.Information => [" [", "Info", "] "],
LogLevel.Warning => [" [", "Warn", "] "],
LogLevel.Error => ["[", "Error", "] "],
LogLevel.Critical => [" [", "\e[1mCrit\e[0m", "] "],
_ => [" [", "None", "] "],
};
using Lock.Scope _ = consoleLock.EnterScope();
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("[");
Console.ResetColor();
Console.ForegroundColor = GetLogLevelColour(logLevel);
if (logLevel == LogLevel.Critical)
{
Console.BackgroundColor = ConsoleColor.DarkRed;
}
Console.Write($"{DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")}");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("] ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("[");
Console.ForegroundColor = IsSingleton ? ConsoleColor.Green : ConsoleColor.DarkGreen;
Console.Write(IsSingleton ? "BOT" : "API");
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("] ");
Console.Write(logLevelParts[0]);
Console.ForegroundColor = GetLogLevelColour(logLevel);
if (logLevel == LogLevel.Critical)
{
Console.BackgroundColor = ConsoleColor.DarkRed;
}
Console.Write(logLevelParts[1]);
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(logLevelParts[2]);
Console.ResetColor();
if (logLevel is LogLevel.Trace or LogLevel.Debug)
{
Console.ForegroundColor = ConsoleColor.Gray;
}
else if (logLevel is LogLevel.Critical or LogLevel.Error)
{
Console.ForegroundColor = ConsoleColor.Red;
}
Console.WriteLine(message);
if (exception != null)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(GetExceptionString(exception, 0));
}
Console.ResetColor();
}
private void LogToFile(LogLevel logLevel, string message, Exception exception, bool skipCache = false)
{
// Don't do anything if the config is loaded and we didn't set up a log file
if (Config.Initialized && logFileWriter == null)
{
return;
}
string logLevelTag = logLevel switch
{
LogLevel.Trace => "[Trace] ",
LogLevel.Debug => "[Debug] ",
LogLevel.Information => " [Info] ",
LogLevel.Warning => " [Warn] ",
LogLevel.Error => "[Error] ",
LogLevel.Critical => " [\e[1mCrit\e[0m] ",
_ => " [None] ",
};
// Add prefix
string logMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + logLevelTag + (IsSingleton ? "[BOT] " : "[API] ");
int prefixLength = logMessage.Length;
// Add message with indentation
logMessage += message.Replace("\n", "\n" + new string(' ', prefixLength));
if (exception != null)
{
logMessage += "\n" + GetExceptionString(exception, 0);
}
using Lock.Scope _ = fileLock.EnterScope();
if (!Config.Initialized && !skipCache || logFileWriter == null)
{
startupCache.Add(logMessage);
return;
}
try
{
logFileWriter.WriteLine(logMessage);
logFileWriter.Flush();
}
catch (Exception e)
{
Instance.LogToConsoleOrSystemd(LogLevel.Error, "Error writing to log file.", e);
}
}
internal static void SetupLogfile()
{
using Lock.Scope _ = fileLock.EnterScope();
if (string.IsNullOrWhiteSpace(Config.LogPath))
{
startupCache.Clear();
logFileWriter?.Close();
logFileWriter = null;
return;
}
if (File.Exists(Config.LogPath))
{
try
{
logFileWriter = File.AppendText(Path.GetFullPath(Config.LogPath));
// Create some empty rows between bot runs in the log file
Instance.LogToFile(LogLevel.Information, "", null, true);
Instance.LogToFile(LogLevel.Information, "", null, true);
Instance.LogToFile(LogLevel.Information, "", null, true);
Instance.LogToFile(LogLevel.Information, "", null, true);
Log($"Opened log file \"{Path.GetFullPath(Config.LogPath)}\".");
}
catch (Exception e)
{
Instance.LogToConsoleOrSystemd(LogLevel.Error, "Error opening log file \"" + Path.GetFullPath(Config.LogPath) + "\".", e);
return;
}
}
else
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(Config.LogPath)));
}
catch (Exception e)
{
Instance.LogToConsoleOrSystemd(LogLevel.Error, "Error creating log file directory \"" + Path.GetDirectoryName(Path.GetFullPath(Config.LogPath)) + "\".", e);
}
try
{
logFileWriter = File.CreateText(Path.GetFullPath(Config.LogPath));
Log($"Created log file \"{Path.GetFullPath(Config.LogPath)}\".");
}
catch (Exception e)
{
Instance.LogToConsoleOrSystemd(LogLevel.Error, "Error creating log file \"" + Path.GetFullPath(Config.LogPath) + "\".", e);
return;
}
}
// Create a notice at the start of every run
Instance.LogToFile(LogLevel.Information, "###################################", null, true);
Instance.LogToFile(LogLevel.Information, "########## BOT STARTUP ##########", null, true);
Instance.LogToFile(LogLevel.Information, "###################################", null, true);
try
{
foreach (string line in startupCache)
{
logFileWriter.WriteLine(line);
}
logFileWriter.Flush();
}
catch (Exception e)
{
Instance.LogToConsoleOrSystemd(LogLevel.Error, "Error writing cache to log file.", e);
}
startupCache.Clear();
}
private static string GetExceptionString(Exception exception, int indentation = 0)
{
string exceptionString = $"{new string(' ', indentation)}{exception}: {exception.Message}";
// Add stack trace if it is not included in the message
if (exception.StackTrace != null && !exceptionString.Contains(exception.StackTrace))
{
exceptionString += $"\n{exception.StackTrace}";
}
return exceptionString.Replace("\n", "\n" + new string(' ', indentation));
}
}