No more static

This commit is contained in:
Mira 2022-06-13 10:26:26 +02:00
parent f441a104c9
commit d8272c36a1
Signed by untrusted user who does not match committer: Xorog
GPG key ID: 983798ED9C3E7C36
6 changed files with 118 additions and 113 deletions

9
Entities/LogEntry.cs Normal file
View file

@ -0,0 +1,9 @@
namespace Xorog.Logger.Entities;
public class LogEntry
{
public DateTime TimeOfEvent { get; set; }
public LogLevel LogLevel { get; set; }
public string Message { get; set; }
public Exception? Exception { get; set; }
}

14
Enums/LogLevel.cs Normal file
View file

@ -0,0 +1,14 @@
namespace Xorog.Logger.Enums;
public enum LogLevel
{
NONE,
FATAL,
ERROR,
WARN,
INFO,
DEBUG,
DEBUG2,
TRACE,
TRACE2
}

View file

@ -2,6 +2,6 @@ namespace Xorog.Logger;
public class LogMessageEventArgs : EventArgs public class LogMessageEventArgs : EventArgs
{ {
public LoggerObjects.LogEntry LogEntry { get; set; } public LogEntry LogEntry { get; set; }
} }

10
Global.cs Normal file
View file

@ -0,0 +1,10 @@
global using Microsoft.Extensions.Logging;
global using System;
global using System.Collections.Generic;
global using System.IO;
global using System.Linq;
global using System.Text;
global using System.Threading.Tasks;
global using Xorog.Logger.Entities;
global using Xorog.Logger.Enums;
global using LogLevel = Xorog.Logger.Enums.LogLevel;

167
Logger.cs
View file

@ -1,23 +1,22 @@
using System.Text; namespace Xorog.Logger;
using System.IO;
using static Xorog.Logger.LoggerObjects;
using Microsoft.Extensions.Logging;
namespace Xorog.Logger;
public class Logger : ILogger public class Logger : ILogger
{ {
private static bool loggerStarted = false; internal Logger() { }
private static LoggerObjects.LogLevel maxLogLevel = LoggerObjects.LogLevel.DEBUG;
private static string FileName = ""; private bool loggerStarted = false;
private static FileStream OpenedFile { get; set; } private LogLevel maxLogLevel = LogLevel.DEBUG;
private readonly static LoggerObjects _loggerObjects = new(); private string FileName = "";
private FileStream OpenedFile { get; set; }
private static Task RunningLogger = null; internal List<LogEntry> LogsToPost = new();
internal List<string> Blacklist = new();
internal List<LogLevel> FileBlackList = new();
public static event EventHandler<LogMessageEventArgs> LogRaised; private Task RunningLogger = null;
public event EventHandler<LogMessageEventArgs> LogRaised;
/// <summary> /// <summary>
@ -27,19 +26,21 @@ public class Logger : ILogger
/// <param name="level">The loglevel that should be displayed in the console, does not affect whats written to file</param> /// <param name="level">The loglevel that should be displayed in the console, does not affect whats written to file</param>
/// <param name="cleanUpBefore">Clean up old logs before a datetime</param> /// <param name="cleanUpBefore">Clean up old logs before a datetime</param>
/// <returns>A bool stating if the logger was started</returns> /// <returns>A bool stating if the logger was started</returns>
public static ILogger StartLogger(string filePath = "", LoggerObjects.LogLevel level = LoggerObjects.LogLevel.DEBUG, DateTime cleanUpBefore = new DateTime(), bool ThrowOnFailedDeletion = false) public static Logger StartLogger(string filePath = "", LogLevel level = LogLevel.DEBUG, DateTime cleanUpBefore = new DateTime(), bool ThrowOnFailedDeletion = false)
{ {
if (loggerStarted) var handler = new Logger();
if (handler.loggerStarted)
throw new Exception($"The logger is already started"); throw new Exception($"The logger is already started");
if (filePath is not "") if (filePath is not "")
{ {
FileName = filePath; handler.FileName = filePath;
OpenedFile = File.Open(FileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read); handler.OpenedFile = File.Open(handler.FileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read);
} }
loggerStarted = true; handler.loggerStarted = true;
maxLogLevel = level; handler.maxLogLevel = level;
if (cleanUpBefore != new DateTime()) if (cleanUpBefore != new DateTime())
{ {
@ -51,34 +52,34 @@ public class Logger : ILogger
if (fi.CreationTimeUtc < cleanUpBefore) if (fi.CreationTimeUtc < cleanUpBefore)
{ {
fi.Delete(); fi.Delete();
LogDebug($"{fi.Name} deleted"); handler.LogDebug($"{fi.Name} deleted");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
if (!ThrowOnFailedDeletion) if (!ThrowOnFailedDeletion)
LogError( $"Couldn't delete log file {b}", ex); handler.LogError( $"Couldn't delete log file {b}", ex);
else else
throw new Exception($"Failed to delete {b}: {ex}"); throw new Exception($"Failed to delete {b}: {ex}");
} }
} }
} }
RunningLogger = Task.Run(async () => handler.RunningLogger = Task.Run(async () =>
{ {
while (loggerStarted) while (handler.loggerStarted)
{ {
try try
{ {
while (_loggerObjects.LogsToPost.Count == 0) while (handler.LogsToPost.Count == 0)
{ {
Thread.Sleep(10); Thread.Sleep(10);
} }
for (int i = 0; i < _loggerObjects.LogsToPost.Count; i++) for (int i = 0; i < handler.LogsToPost.Count; i++)
{ {
var currentLog = _loggerObjects.LogsToPost[0]; var currentLog = handler.LogsToPost[0];
_loggerObjects.LogsToPost.Remove(currentLog); handler.LogsToPost.Remove(currentLog);
if (currentLog is null) if (currentLog is null)
@ -96,28 +97,28 @@ public class Logger : ILogger
LogLevelColor = currentLog.LogLevel switch LogLevelColor = currentLog.LogLevel switch
{ {
LoggerObjects.LogLevel.TRACE => ConsoleColor.Gray, LogLevel.TRACE => ConsoleColor.Gray,
LoggerObjects.LogLevel.DEBUG2 => ConsoleColor.Gray, LogLevel.DEBUG2 => ConsoleColor.Gray,
LoggerObjects.LogLevel.DEBUG => ConsoleColor.Gray, LogLevel.DEBUG => ConsoleColor.Gray,
LoggerObjects.LogLevel.INFO => ConsoleColor.Green, LogLevel.INFO => ConsoleColor.Green,
LoggerObjects.LogLevel.WARN => ConsoleColor.Yellow, LogLevel.WARN => ConsoleColor.Yellow,
LoggerObjects.LogLevel.ERROR => ConsoleColor.Red, LogLevel.ERROR => ConsoleColor.Red,
LoggerObjects.LogLevel.FATAL => ConsoleColor.Black, LogLevel.FATAL => ConsoleColor.Black,
_ => ConsoleColor.Gray _ => ConsoleColor.Gray
}; };
BackgroundColor = currentLog.LogLevel switch BackgroundColor = currentLog.LogLevel switch
{ {
LoggerObjects.LogLevel.FATAL => ConsoleColor.DarkRed, LogLevel.FATAL => ConsoleColor.DarkRed,
_ => ConsoleColor.Black _ => ConsoleColor.Black
}; };
string LogMessage = currentLog.Message; string LogMessage = currentLog.Message;
foreach (var blacklistobject in _loggerObjects.Blacklist) foreach (var blacklistobject in handler.Blacklist)
LogMessage = LogMessage.Replace(blacklistobject, new String('*', blacklistobject.Length), StringComparison.CurrentCultureIgnoreCase); LogMessage = LogMessage.Replace(blacklistobject, new String('*', blacklistobject.Length), StringComparison.CurrentCultureIgnoreCase);
if (maxLogLevel >= currentLog.LogLevel) if (handler.maxLogLevel >= currentLog.LogLevel)
{ {
Console.ResetColor(); Console.Write($"[{currentLog.TimeOfEvent:dd.MM.yyyy HH:mm:ss}] "); Console.ResetColor(); Console.Write($"[{currentLog.TimeOfEvent:dd.MM.yyyy HH:mm:ss}] ");
Console.ForegroundColor = LogLevelColor; Console.BackgroundColor = BackgroundColor; Console.Write($"[{LogLevelText}]"); Console.ForegroundColor = LogLevelColor; Console.BackgroundColor = BackgroundColor; Console.Write($"[{LogLevelText}]");
@ -129,30 +130,30 @@ public class Logger : ILogger
_ = Task.Run(() => _ = Task.Run(() =>
{ {
LogRaised?.Invoke(null, new LogMessageEventArgs() { LogEntry = currentLog }); handler.LogRaised?.Invoke(null, new LogMessageEventArgs() { LogEntry = currentLog });
}); });
try try
{ {
if (!_loggerObjects.FileBlackList.Contains(currentLog.LogLevel)) if (!handler.FileBlackList.Contains(currentLog.LogLevel))
{ {
Byte[] FileWrite = Encoding.UTF8.GetBytes($"[{currentLog.TimeOfEvent:dd.MM.yyyy HH:mm:ss}] [{LogLevelText}] {LogMessage}\n{(currentLog.Exception is not null ? $"{currentLog.Exception}\n" : "")}"); Byte[] FileWrite = Encoding.UTF8.GetBytes($"[{currentLog.TimeOfEvent:dd.MM.yyyy HH:mm:ss}] [{LogLevelText}] {LogMessage}\n{(currentLog.Exception is not null ? $"{currentLog.Exception}\n" : "")}");
if (OpenedFile != null) if (handler.OpenedFile != null)
{ {
await OpenedFile.WriteAsync(FileWrite.AsMemory(0, FileWrite.Length)); await handler.OpenedFile.WriteAsync(FileWrite.AsMemory(0, FileWrite.Length));
OpenedFile.Flush(); handler.OpenedFile.Flush();
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
LogFatal($"Couldn't write log to file: {ex}"); handler.LogFatal($"Couldn't write log to file: {ex}");
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
LogError("An exception occured while trying to display a log message", ex); handler.LogError("An exception occured while trying to display a log message", ex);
await Task.Delay(1000); await Task.Delay(1000);
continue; continue;
} }
@ -167,10 +168,10 @@ public class Logger : ILogger
/// <summary> /// <summary>
/// Stops the logger /// Stops the logger
/// </summary> /// </summary>
public static void StopLogger() public void StopLogger()
{ {
loggerStarted = false; loggerStarted = false;
maxLogLevel = LoggerObjects.LogLevel.DEBUG; maxLogLevel = LogLevel.DEBUG;
FileName = ""; FileName = "";
Thread.Sleep(500); Thread.Sleep(500);
@ -190,18 +191,18 @@ public class Logger : ILogger
/// Add blacklisted string to censor automatically /// Add blacklisted string to censor automatically
/// </summary> /// </summary>
/// <param name="blacklist"></param> /// <param name="blacklist"></param>
public static void AddBlacklist(string blacklist) public void AddBlacklist(string blacklist)
{ {
_loggerObjects.Blacklist.Add(blacklist); Blacklist.Add(blacklist);
} }
/// <summary> /// <summary>
/// Add blacklisted log level to not save /// Add blacklisted log level to not save
/// </summary> /// </summary>
/// <param name="blacklist"></param> /// <param name="blacklist"></param>
public static void AddLogLevelBlacklist(LoggerObjects.LogLevel level) public void AddLogLevelBlacklist(LogLevel level)
{ {
_loggerObjects.FileBlackList.Add(level); FileBlackList.Add(level);
} }
@ -210,7 +211,7 @@ public class Logger : ILogger
/// Changes the log level /// Changes the log level
/// </summary> /// </summary>
/// <param name="level"></param> /// <param name="level"></param>
public static void ChangeLogLevel(LoggerObjects.LogLevel level) public void ChangeLogLevel(LogLevel level)
{ {
maxLogLevel = level; maxLogLevel = level;
} }
@ -222,12 +223,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogNone(string message, Exception? exception = null) public void LogNone(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.NONE, LogLevel = LogLevel.NONE,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -240,12 +241,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogTrace(string message, Exception? exception = null) public void LogTrace(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.TRACE, LogLevel = LogLevel.TRACE,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -258,12 +259,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogDebug2(string message, Exception? exception = null) public void LogDebug2(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.DEBUG2, LogLevel = LogLevel.DEBUG2,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -276,12 +277,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogDebug(string message, Exception? exception = null) public void LogDebug(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.DEBUG, LogLevel = LogLevel.DEBUG,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -294,12 +295,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogInfo(string message, Exception? exception = null) public void LogInfo(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.INFO, LogLevel = LogLevel.INFO,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -312,12 +313,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogWarn(string message, Exception? exception = null) public void LogWarn(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.WARN, LogLevel = LogLevel.WARN,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -330,12 +331,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogError(string message, Exception? exception = null) public void LogError(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.ERROR, LogLevel = LogLevel.ERROR,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -348,12 +349,12 @@ public class Logger : ILogger
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="message"></param> /// <param name="message"></param>
public static void LogFatal(string message, Exception? exception = null) public void LogFatal(string message, Exception? exception = null)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = LoggerObjects.LogLevel.FATAL, LogLevel = LogLevel.FATAL,
Message = message, Message = message,
Exception = exception Exception = exception
}); });
@ -371,18 +372,18 @@ public class Logger : ILogger
/// <param name="formatter"></param> /// <param name="formatter"></param>
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{ {
_loggerObjects.LogsToPost.Add(new LoggerObjects.LogEntry LogsToPost.Add(new LogEntry
{ {
TimeOfEvent = DateTime.Now, TimeOfEvent = DateTime.Now,
LogLevel = logLevel switch LogLevel = logLevel switch
{ {
Microsoft.Extensions.Logging.LogLevel.Debug => LoggerObjects.LogLevel.DEBUG2, Microsoft.Extensions.Logging.LogLevel.Debug => LogLevel.DEBUG2,
Microsoft.Extensions.Logging.LogLevel.Trace => LoggerObjects.LogLevel.TRACE2, Microsoft.Extensions.Logging.LogLevel.Trace => LogLevel.TRACE2,
Microsoft.Extensions.Logging.LogLevel.Information => LoggerObjects.LogLevel.INFO, Microsoft.Extensions.Logging.LogLevel.Information => LogLevel.INFO,
Microsoft.Extensions.Logging.LogLevel.Warning => LoggerObjects.LogLevel.WARN, Microsoft.Extensions.Logging.LogLevel.Warning => LogLevel.WARN,
Microsoft.Extensions.Logging.LogLevel.Error => LoggerObjects.LogLevel.ERROR, Microsoft.Extensions.Logging.LogLevel.Error => LogLevel.ERROR,
Microsoft.Extensions.Logging.LogLevel.Critical => LoggerObjects.LogLevel.FATAL, Microsoft.Extensions.Logging.LogLevel.Critical => LogLevel.FATAL,
Microsoft.Extensions.Logging.LogLevel.None => LoggerObjects.LogLevel.NONE, Microsoft.Extensions.Logging.LogLevel.None => LogLevel.NONE,
_ => throw new NotImplementedException() _ => throw new NotImplementedException()
}, },
Message = $"[{eventId.Id,2}] {formatter(state, exception)}", Message = $"[{eventId.Id,2}] {formatter(state, exception)}",

View file

@ -1,29 +0,0 @@
namespace Xorog.Logger;
public class LoggerObjects
{
internal List<LogEntry> LogsToPost = new();
internal List<string> Blacklist = new();
internal List<LogLevel> FileBlackList = new();
public class LogEntry
{
public DateTime TimeOfEvent { get; set; }
public LogLevel LogLevel { get; set; }
public string Message { get; set; }
public Exception? Exception { get; set; }
}
public enum LogLevel
{
NONE,
FATAL,
ERROR,
WARN,
INFO,
DEBUG,
DEBUG2,
TRACE,
TRACE2
}
}