Compare commits

...
This repository has been archived on 2026-06-12. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.

3 commits
main ... legacy

Author SHA1 Message Date
Mira
bbf207a2b6
Update README.md 2022-06-13 10:39:55 +02:00
Mira
49b3083f9c
Update README.md 2022-06-13 10:39:31 +02:00
Mira
84c0a25912
Revert "No more static"
This reverts commit d8272c36a1.
2022-06-13 10:27:21 +02:00
7 changed files with 116 additions and 119 deletions

View file

@ -1,9 +0,0 @@
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; }
}

View file

@ -1,14 +0,0 @@
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 LogEntry LogEntry { get; set; } public LoggerObjects.LogEntry LogEntry { get; set; }
} }

View file

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

29
LoggerObjects.cs Normal file
View file

@ -0,0 +1,29 @@
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
}
}

View file

@ -1 +1,3 @@
# Xorog.Logger # Xorog.Logger
This legacy branch is meant to prevent having to update way too many applications because of a few breaking changes to main.