diff --git a/EonaCat.Logger/EonaCat.Logger.csproj b/EonaCat.Logger/EonaCat.Logger.csproj
index 674c26f..1066dd7 100644
--- a/EonaCat.Logger/EonaCat.Logger.csproj
+++ b/EonaCat.Logger/EonaCat.Logger.csproj
@@ -8,7 +8,7 @@
net7.0;
icon.ico
- 1.1.0
+ 1.1.1
EonaCat (Jeroen Saey)
true
EonaCat (Jeroen Saey)
diff --git a/EonaCat.Logger/Managers/LogHelper.cs b/EonaCat.Logger/Managers/LogHelper.cs
index 5bd3da2..4b2869f 100644
--- a/EonaCat.Logger/Managers/LogHelper.cs
+++ b/EonaCat.Logger/Managers/LogHelper.cs
@@ -16,70 +16,45 @@ namespace EonaCat.Logger.Managers
{
private static readonly object FileLock = new object();
- ///
- /// Format a message with the specified header
- ///
- /// Logger settings
- /// logtype for the formatted message
- /// The actual message to format with the header
- /// The dateTime of the message
- ///
- public static string FormatMessageWithHeader(LoggerSettings settings, ELogType logType, string currentMessage, DateTime dateTime)
+ internal static string FormatMessageWithHeader(LoggerSettings settings, ELogType logType, string currentMessage, DateTime dateTime)
{
if (string.IsNullOrWhiteSpace(currentMessage))
- {
return currentMessage;
- }
- if (settings == null)
- {
- return "[EonaCatLogger]" + " " + currentMessage;
- }
+ string header = settings?.HeaderFormat ?? "[EonaCatLogger]";
- string header = settings.HeaderFormat;
if (header.Contains("{ts}"))
- {
- header = header.Replace("{ts}", dateTime.ToString(settings.TimestampFormat));
- }
+ header = header.Replace("{ts}", dateTime.ToString(settings?.TimestampFormat));
if (header.Contains("{host}"))
- {
header = header.Replace("{host}", Dns.GetHostName());
- }
if (header.Contains("{thread}"))
- {
header = header.Replace("{thread}", Thread.CurrentThread.ManagedThreadId.ToString());
- }
if (header.Contains("{sev}"))
- {
header = header.Replace("{sev}", logType.ToString());
- }
- string fullMessage = AddHeaderIfNotExists(header, currentMessage);
+ string fullMessage = AddHeaderIfNotExists(settings, header, currentMessage);
return fullMessage;
}
- private static string AddHeaderIfNotExists(string header, string currentMessage)
+ private static string AddHeaderIfNotExists(LoggerSettings settings, string header, string currentMessage)
{
- if (!currentMessage.Contains("[EonaCatLogger]"))
+ if (settings == null || !settings.RemoveMessagePrefix)
{
- return "[EonaCatLogger]" + " " + header + " " + currentMessage;
+ if (!currentMessage.Contains("[EonaCatLogger]"))
+ return "[EonaCatLogger] " + header + " " + currentMessage;
}
- return currentMessage;
+
+ return header + " " + currentMessage;
}
- ///
- /// Formats a given exception as a string
- ///
- /// exception
- /// The name of the module which called the code (optional)
- /// The name of the method which waws called in code (optional)
- ///
public static string FormatExceptionToMessage(this Exception exception, string module = null, string method = null)
{
- if (exception == null) return string.Empty;
+ if (exception == null)
+ return string.Empty;
+
var st = new StackTrace(exception, true);
var frame = st.GetFrame(0);
int fileLine = frame.GetFileLineNumber();
@@ -90,49 +65,9 @@ namespace EonaCat.Logger.Managers
"--- Exception details provided by EonaCatLogger ---" + Environment.NewLine +
(!string.IsNullOrEmpty(module) ? " Module : " + module + Environment.NewLine : "") +
(!string.IsNullOrEmpty(method) ? " Method : " + method + Environment.NewLine : "") +
- " Type : " + exception.GetType().ToString() + Environment.NewLine;
-
- if (exception.Data != null && exception.Data.Count > 0)
- {
- message += " Data : " + Environment.NewLine;
- foreach (DictionaryEntry curr in exception.Data)
- {
- message += " | " + curr.Key + ": " + curr.Value + Environment.NewLine;
- }
- }
- else
- {
- message += " Data : (none)" + Environment.NewLine;
- }
-
- message +=
- " Inner : ";
-
- if (exception.InnerException == null) message += "(null)" + Environment.NewLine;
- else
- {
- message += exception.InnerException.GetType().ToString() + Environment.NewLine;
- message +=
- " Message : " + exception.InnerException.Message + Environment.NewLine +
- " Source : " + exception.InnerException.Source + Environment.NewLine +
- " StackTrace : " + exception.InnerException.StackTrace + Environment.NewLine +
- " ToString : " + exception.InnerException.ToString() + Environment.NewLine;
-
- if (exception.InnerException.Data != null && exception.InnerException.Data.Count > 0)
- {
- message += " Data : " + Environment.NewLine;
- foreach (DictionaryEntry curr in exception.Data)
- {
- message += " | " + curr.Key + ": " + curr.Value + Environment.NewLine;
- }
- }
- else
- {
- message += " Data : (none)" + Environment.NewLine;
- }
- }
-
- message +=
+ " Type : " + exception.GetType().ToString() + Environment.NewLine +
+ " Data : " + (exception.Data != null && exception.Data.Count > 0 ? Environment.NewLine + FormatExceptionData(exception.Data) : "(none)") + Environment.NewLine +
+ " Inner : " + (exception.InnerException != null ? FormatInnerException(exception.InnerException) : "(null)") + Environment.NewLine +
" Message : " + exception.Message + Environment.NewLine +
" Source : " + exception.Source + Environment.NewLine +
" StackTrace : " + exception.StackTrace + Environment.NewLine +
@@ -140,14 +75,45 @@ namespace EonaCat.Logger.Managers
" File : " + filename + Environment.NewLine +
" ToString : " + exception.ToString() + Environment.NewLine +
"---";
+
return message;
}
+ private static string FormatExceptionData(IDictionary data)
+ {
+ StringBuilder sb = new StringBuilder();
+
+ foreach (DictionaryEntry entry in data)
+ {
+ sb.Append(" | ")
+ .Append(entry.Key)
+ .Append(": ")
+ .Append(entry.Value)
+ .Append(Environment.NewLine);
+ }
+
+ return sb.ToString();
+ }
+
+ private static string FormatInnerException(Exception innerException)
+ {
+ StringBuilder sb = new StringBuilder();
+
+ sb.AppendLine(innerException.GetType().ToString())
+ .AppendLine(" Message : " + innerException.Message)
+ .AppendLine(" Source : " + innerException.Source)
+ .AppendLine(" StackTrace : " + innerException.StackTrace)
+ .AppendLine(" ToString : " + innerException.ToString())
+ .Append(" Data : ")
+ .AppendLine(innerException.Data != null && innerException.Data.Count > 0 ? Environment.NewLine + FormatExceptionData(innerException.Data) : "(none)");
+
+ return sb.ToString();
+ }
+
internal static void SendConsole(LoggerSettings settings, ELogType logType, string message, bool writeToConsole)
{
- if (settings == null) return;
- if (!writeToConsole) return;
- if (string.IsNullOrWhiteSpace(message)) return;
+ if (settings == null || !writeToConsole || string.IsNullOrWhiteSpace(message))
+ return;
if (settings.EnableColors)
{
@@ -203,10 +169,8 @@ namespace EonaCat.Logger.Managers
{
lock (FileLock)
{
- if (logger == null) return;
- if (settings == null) return;
- if (!settings.EnableFileLogging) return;
- if (string.IsNullOrWhiteSpace(message)) return;
+ if (logger == null || settings == null || !settings.EnableFileLogging || string.IsNullOrWhiteSpace(message))
+ return;
int tries = 0;
bool completed = false;
@@ -214,33 +178,29 @@ namespace EonaCat.Logger.Managers
{
try
{
- if (logType == ELogType.CRITICAL)
+ switch (logType)
{
- logger.LogCritical(message);
- }
- else if (logType == ELogType.DEBUG)
- {
- logger.LogDebug(message);
- }
- else if (logType == ELogType.ERROR)
- {
- logger.LogError(message);
- }
- else if (logType == ELogType.INFO)
- {
- logger.LogInformation(message);
- }
- else if (logType == ELogType.TRACE)
- {
- logger.LogTrace(message);
- }
- else if (logType == ELogType.TRAFFIC)
- {
- logger.LogTrace($"[TRAFFIC] {message}");
- }
- else if (logType == ELogType.WARNING)
- {
- logger.LogWarning(message);
+ case ELogType.CRITICAL:
+ logger.LogCritical(message);
+ break;
+ case ELogType.DEBUG:
+ logger.LogDebug(message);
+ break;
+ case ELogType.ERROR:
+ logger.LogError(message);
+ break;
+ case ELogType.INFO:
+ logger.LogInformation(message);
+ break;
+ case ELogType.TRACE:
+ logger.LogTrace(message);
+ break;
+ case ELogType.TRAFFIC:
+ logger.LogTrace($"[TRAFFIC] {message}");
+ break;
+ case ELogType.WARNING:
+ logger.LogWarning(message);
+ break;
}
completed = true;
}
@@ -251,15 +211,14 @@ namespace EonaCat.Logger.Managers
if (tries >= maxTries)
throw;
}
- }
+ }
}
}
internal static void SendToSysLogServers(LoggerSettings settings, string message)
{
- if (settings == null) return;
- if (!settings.SendToSyslogServers) return;
- if (string.IsNullOrWhiteSpace(message)) return;
+ if (settings == null || !settings.SendToSyslogServers || string.IsNullOrWhiteSpace(message))
+ return;
if (settings.SysLogServers == null || !settings.SysLogServers.Any())
{
@@ -294,4 +253,5 @@ namespace EonaCat.Logger.Managers
}
}
}
+
}
\ No newline at end of file
diff --git a/EonaCat.Logger/Managers/LogManager.cs b/EonaCat.Logger/Managers/LogManager.cs
index 14c7c01..9f5d65f 100644
--- a/EonaCat.Logger/Managers/LogManager.cs
+++ b/EonaCat.Logger/Managers/LogManager.cs
@@ -1,5 +1,4 @@
using EonaCat.Logger.Exceptions;
-using EonaCat.Logger.Helpers;
using EonaCat.Logger.Syslog;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -20,66 +19,42 @@ namespace EonaCat.Logger.Managers
public partial class LogManager : ILogManager, IDisposable
{
private DateTime _logDate;
- public ELogType LogType;
- private ILoggerProvider LoggerProvider { get; set; }
- private ILoggerFactory LoggerFactory { get; set; }
- private ILogger Logger { get; set; }
- public string CurrentLogFile => LoggerProvider != null ? ((FileLoggerProvider)LoggerProvider).LogFile : string.Empty;
+ public ILoggerProvider LoggerProvider { get; private set; }
+ public ILoggerFactory LoggerFactory { get; private set; }
+ public ILogger Logger { get; private set; }
+ public string CurrentLogFile => LoggerProvider is FileLoggerProvider fileLoggerProvider ? fileLoggerProvider.LogFile : string.Empty;
public bool IsRunning { get; private set; }
-
- public StreamWriter Output { get; private set; }
-
public string CategoryName { get; set; }
-
- public readonly string Id;
+ public string Id { get; }
private bool _disposed;
private static LogManager _instance;
private LoggerSettings _settings;
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
- private CancellationToken _token;
- ///
- /// Default Logger Instance with it's default configuration
- ///
public static LogManager Instance => InstanceInit();
- ///
- /// Logging settings.
- ///
public LoggerSettings Settings
{
get
{
- if (_settings == null)
- {
- _settings = new LoggerSettings();
- }
+ _settings ??= new LoggerSettings();
return _settings;
}
-
- set
- {
- _settings = value;
- }
+ set => _settings = value;
}
private static LogManager InstanceInit()
{
- if (_instance == null)
- {
- _instance = new LogManager(null, id: "EonaCat");
- }
+ _instance ??= new LogManager(null, id: "EonaCat");
return _instance;
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
- {
return;
- }
if (disposing)
{
@@ -93,43 +68,38 @@ namespace EonaCat.Logger.Managers
private void StartNewLog()
{
if (_tokenSource.IsCancellationRequested)
- {
return;
- }
- DateTime now = DateTime.Now;
+ DateTime now = DateTime.UtcNow;
if (IsRunning && now.Date > _logDate.Date)
- {
StopLogging();
- }
+
IsRunning = true;
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder => builder.AddEonaCatFileLogger(configuration =>
{
- configuration.MaxWriteTries = Settings.FileLoggerOptions.MaxWriteTries;
- configuration.RetainedFileCountLimit = Settings.FileLoggerOptions.RetainedFileCountLimit;
- configuration.FlushPeriod = Settings.FileLoggerOptions.FlushPeriod;
- configuration.IsEnabled = Settings.FileLoggerOptions.IsEnabled;
- configuration.BatchSize = Settings.FileLoggerOptions.BatchSize;
- configuration.FileSizeLimit = Settings.FileLoggerOptions.FileSizeLimit;
- configuration.LogDirectory = Settings.FileLoggerOptions.LogDirectory;
- configuration.FileNamePrefix = Settings.FileLoggerOptions.FileNamePrefix;
- configuration.MaxRolloverFiles = Settings.FileLoggerOptions.MaxRolloverFiles;
+ var fileLoggerOptions = Settings.FileLoggerOptions;
+ configuration.MaxWriteTries = fileLoggerOptions.MaxWriteTries;
+ configuration.RetainedFileCountLimit = fileLoggerOptions.RetainedFileCountLimit;
+ configuration.FlushPeriod = fileLoggerOptions.FlushPeriod;
+ configuration.IsEnabled = fileLoggerOptions.IsEnabled;
+ configuration.BatchSize = fileLoggerOptions.BatchSize;
+ configuration.FileSizeLimit = fileLoggerOptions.FileSizeLimit;
+ configuration.LogDirectory = fileLoggerOptions.LogDirectory;
+ configuration.FileNamePrefix = fileLoggerOptions.FileNamePrefix;
+ configuration.MaxRolloverFiles = fileLoggerOptions.MaxRolloverFiles;
}));
var serviceProvider = serviceCollection.BuildServiceProvider();
LoggerProvider = serviceProvider.GetService();
LoggerFactory = serviceProvider.GetService();
- CategoryName = CategoryName ?? string.Empty;
+ CategoryName ??= string.Empty;
Logger = LoggerFactory.CreateLogger(CategoryName);
- if (!Directory.Exists(Settings.FileLoggerOptions.LogDirectory))
- {
- Directory.CreateDirectory(Settings.FileLoggerOptions.LogDirectory);
- }
+ Directory.CreateDirectory(Settings.FileLoggerOptions.LogDirectory);
_logDate = now;
@@ -139,60 +109,35 @@ namespace EonaCat.Logger.Managers
public void Assert(bool condition, string message)
{
if (!condition)
- {
throw new EonaCatLoggerAssertionException(message);
- }
}
private void Write(DateTime dateTime, string message, ELogType logType = ELogType.INFO, bool? writeToConsole = null)
{
- if (string.IsNullOrWhiteSpace(message)) return;
- if (logType < ELogType.INFO) return;
+ if (string.IsNullOrEmpty(message) || logType < ELogType.INFO)
+ return;
- string remainder = "";
- string currentMessage;
-
- if (message.Length > _settings.MaxMessageLength)
- {
- currentMessage = message.Substring(0, _settings.MaxMessageLength);
- remainder = message.Substring(_settings.MaxMessageLength, (message.Length - _settings.MaxMessageLength));
- }
- else
- {
- currentMessage = message;
- }
+ string currentMessage = message.Length > _settings.MaxMessageLength ? message.Substring(0, _settings.MaxMessageLength) : message;
+ string remainder = message.Length > _settings.MaxMessageLength ? message.Substring(_settings.MaxMessageLength) : "";
var fullMessage = LogHelper.FormatMessageWithHeader(_settings, logType, currentMessage, dateTime);
- if (writeToConsole == null)
- {
- writeToConsole = _settings.EnableConsole;
- }
-
- LogHelper.SendConsole(_settings, logType, fullMessage, writeToConsole == true);
-
+ writeToConsole ??= _settings.EnableConsole;
+ LogHelper.SendConsole(_settings, logType, fullMessage, writeToConsole.Value);
LogHelper.SendFile(Logger, _settings, logType, fullMessage);
-
LogHelper.SendToSysLogServers(_settings, fullMessage);
if (!string.IsNullOrEmpty(remainder))
- {
Write(dateTime, remainder, logType, writeToConsole);
- }
var logMessage = new EonaCatLogMessage
{
DateTime = dateTime,
Message = currentMessage,
- LogType = logType
+ LogType = logType,
+ Origin = string.IsNullOrWhiteSpace(Settings?.LogOrigin) ? "LogManager" : Settings.LogOrigin
};
- if (Settings != null)
- {
- logMessage.Origin = string.IsNullOrWhiteSpace(Settings.LogOrigin) ? "LogManager" : Settings.LogOrigin;
- Settings?.OnLogEvent(logMessage);
- }
-
Settings?.OnLogEvent(logMessage);
}
@@ -200,13 +145,16 @@ namespace EonaCat.Logger.Managers
public LogManager(LoggerSettings settings, string serverIp, int serverPort, string id = "EonaCatLogger")
{
- if (string.IsNullOrEmpty(serverIp)) throw new ArgumentNullException(nameof(serverIp));
- if (serverPort < 0) throw new ArgumentException("Server port must be zero or greater.");
+ if (string.IsNullOrEmpty(serverIp))
+ throw new ArgumentNullException(nameof(serverIp));
+
+ if (serverPort < 0)
+ throw new ArgumentException("Server port must be zero or greater.");
settings.SysLogServers = new List
- {
- new SyslogServer(serverIp, serverPort)
- };
+ {
+ new SyslogServer(serverIp, serverPort)
+ };
Id = id;
Settings = settings;
@@ -224,43 +172,26 @@ namespace EonaCat.Logger.Managers
private void SetupFileLogger(LoggerSettings settings = null, string logFolder = null, bool defaultPrefix = true)
{
if (settings == null)
- {
- // Create default loggingSettings
- Settings = settings;
settings = Settings;
- }
- if (!settings.EnableFileLogging) return;
+ if (!settings.EnableFileLogging)
+ return;
if (logFolder != null)
- {
- Settings.FileLoggerOptions.LogDirectory = logFolder;
- }
+ settings.FileLoggerOptions.LogDirectory = logFolder;
- if (string.IsNullOrWhiteSpace(Settings.FileLoggerOptions.FileNamePrefix))
- {
- if (defaultPrefix)
- {
- Settings.FileLoggerOptions.FileNamePrefix = "EonaCat";
- }
- else
- {
- Settings.FileLoggerOptions.FileNamePrefix = string.Empty;
- }
- }
+ if (string.IsNullOrWhiteSpace(settings.FileLoggerOptions.FileNamePrefix))
+ settings.FileLoggerOptions.FileNamePrefix = defaultPrefix ? "EonaCat" : string.Empty;
}
private void SetupLogManager()
{
- _token = _tokenSource.Token;
AppDomain.CurrentDomain.ProcessExit += ProcessExit;
-
- Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
-
- _logDate = DateTime.Now;
+ Console.CancelKeyPress += Console_CancelKeyPress;
+ _logDate = DateTime.UtcNow;
}
- void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
+ private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Dispose(true);
}
@@ -273,8 +204,8 @@ namespace EonaCat.Logger.Managers
private void StopLogging()
{
IsRunning = false;
- Write(DateTime.Now, $"{DllInfo.ApplicationName} stopped.");
- Task.Delay(500, _token);
+ Write(DateTime.UtcNow, $"{DllInfo.ApplicationName} stopped.");
+ Task.Delay(500, _tokenSource.Token);
}
public LogManager(string logFolder = null, bool defaultPrefix = true)
@@ -285,23 +216,21 @@ namespace EonaCat.Logger.Managers
public void Write(Exception exception, string module = null, string method = null, bool criticalException = false, bool? writeToConsole = null)
{
- if (exception == null) return;
+ if (exception == null)
+ return;
+
Write(exception.FormatExceptionToMessage(module, method), criticalException ? ELogType.CRITICAL : ELogType.ERROR, writeToConsole);
}
public void Write(string message, ELogType logType = ELogType.INFO, bool? writeToConsole = null)
{
if (logType == ELogType.NONE)
- {
return;
- }
- DateTime now = DateTime.Now;
+ DateTime now = DateTime.UtcNow;
if (!IsRunning)
- {
StartNewLog();
- }
Write(now, message, logType, writeToConsole);
}
@@ -309,14 +238,14 @@ namespace EonaCat.Logger.Managers
public void DeleteCurrentLogFile()
{
if (!string.IsNullOrWhiteSpace(CurrentLogFile))
- {
File.Delete(CurrentLogFile);
- }
}
- void IDisposable.Dispose()
+ public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
}
+
}
\ No newline at end of file
diff --git a/EonaCat.Logger/Managers/LoggerSettings.cs b/EonaCat.Logger/Managers/LoggerSettings.cs
index c5bada9..d3f219c 100644
--- a/EonaCat.Logger/Managers/LoggerSettings.cs
+++ b/EonaCat.Logger/Managers/LoggerSettings.cs
@@ -14,6 +14,11 @@ namespace EonaCat.Logger.Managers
public event LogDelegate OnLog;
public delegate void LogDelegate(EonaCatLogMessage message);
+ ///
+ /// Determines if we need to remove the prefix [EonaCatLogger] from each message (default: false)
+ ///
+ public bool RemoveMessagePrefix { get; set; }
+
///
/// Header format. Provide a string that specifies how the preamble of each message should be structured. You can use variables including:
@@ -148,7 +153,7 @@ namespace EonaCat.Logger.Managers
}
///
- /// Set the origin of where the OnLog event was inititated
+ /// Set the origin of where the OnLog event was initiated
///
public string LogOrigin { get; set; }
@@ -159,7 +164,7 @@ namespace EonaCat.Logger.Managers
private ColorSchema _colors = new ColorSchema();
- private bool ConsoleExists()
+ private static bool ConsoleExists()
{
try
{