300 lines
12 KiB
C#
300 lines
12 KiB
C#
using EonaCat.Logger;
|
|
using EonaCat.Logger.Managers;
|
|
using EonaCat.Logger.Syslog;
|
|
using Microsoft.Extensions.Logging;
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace EonaCat.logger.Managers
|
|
{
|
|
public static class LogHelper
|
|
{
|
|
private static readonly object _fileLock = new object();
|
|
|
|
/// <summary>
|
|
/// Format a message with the specified header
|
|
/// </summary>
|
|
/// <param name="settings">Logger settings</param>
|
|
/// <param name="logType">logtype for the formatted message</param>
|
|
/// <param name="currentMessage">The actual message to format with the header</param>
|
|
/// <param name="dateTime">The dateTime of the message</param>
|
|
/// <returns></returns>
|
|
public 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;
|
|
if (header.Contains("{ts}"))
|
|
{
|
|
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);
|
|
return fullMessage;
|
|
}
|
|
|
|
private static string AddHeaderIfNotExists(string header, string currentMessage)
|
|
{
|
|
if (!currentMessage.Contains("[EonaCatLogger]"))
|
|
{
|
|
return "[EonaCatLogger]" + " " + header + " " + currentMessage;
|
|
}
|
|
return currentMessage;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Formats a given exception as a string
|
|
/// </summary>
|
|
/// <param name="exception">exception</param>
|
|
/// <param name="module">The name of the module which called the code (optional)</param>
|
|
/// <param name="method">The name of the method which waws called in code (optional)</param>
|
|
/// <returns></returns>
|
|
public static string FormatExceptionToMessage(this Exception exception, string module = null, string method = null)
|
|
{
|
|
if (exception == null) return string.Empty;
|
|
var st = new StackTrace(exception, true);
|
|
var frame = st.GetFrame(0);
|
|
int fileLine = frame.GetFileLineNumber();
|
|
string filename = frame.GetFileName();
|
|
|
|
string message =
|
|
Environment.NewLine +
|
|
"--- [EonaCatLogger] Exception details ---" + 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 +=
|
|
" Message : " + exception.Message + Environment.NewLine +
|
|
" Source : " + exception.Source + Environment.NewLine +
|
|
" StackTrace : " + exception.StackTrace + Environment.NewLine +
|
|
" Line : " + fileLine + Environment.NewLine +
|
|
" File : " + filename + Environment.NewLine +
|
|
" ToString : " + exception.ToString() + Environment.NewLine +
|
|
"---";
|
|
return message;
|
|
}
|
|
|
|
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.EnableColors)
|
|
{
|
|
ConsoleColor prevForeground = Console.ForegroundColor;
|
|
ConsoleColor prevBackground = Console.BackgroundColor;
|
|
|
|
if (settings.Colors != null)
|
|
{
|
|
switch (logType)
|
|
{
|
|
case ELogType.DEBUG:
|
|
Console.ForegroundColor = settings.Colors.Debug.Foreground;
|
|
Console.BackgroundColor = settings.Colors.Debug.Background;
|
|
break;
|
|
case ELogType.INFO:
|
|
Console.ForegroundColor = settings.Colors.Info.Foreground;
|
|
Console.BackgroundColor = settings.Colors.Info.Background;
|
|
break;
|
|
case ELogType.WARNING:
|
|
Console.ForegroundColor = settings.Colors.Warning.Foreground;
|
|
Console.BackgroundColor = settings.Colors.Warning.Background;
|
|
break;
|
|
case ELogType.ERROR:
|
|
Console.ForegroundColor = settings.Colors.Error.Foreground;
|
|
Console.BackgroundColor = settings.Colors.Error.Background;
|
|
break;
|
|
case ELogType.TRAFFIC:
|
|
Console.ForegroundColor = settings.Colors.Traffic.Foreground;
|
|
Console.BackgroundColor = settings.Colors.Traffic.Background;
|
|
break;
|
|
case ELogType.CRITICAL:
|
|
Console.ForegroundColor = settings.Colors.Critical.Foreground;
|
|
Console.BackgroundColor = settings.Colors.Critical.Background;
|
|
break;
|
|
case ELogType.TRACE:
|
|
Console.ForegroundColor = settings.Colors.Trace.Foreground;
|
|
Console.BackgroundColor = settings.Colors.Trace.Background;
|
|
break;
|
|
}
|
|
}
|
|
|
|
Console.WriteLine(message);
|
|
Console.ForegroundColor = prevForeground;
|
|
Console.BackgroundColor = prevBackground;
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine(message);
|
|
}
|
|
}
|
|
|
|
internal static void SendFile(ILogger logger, LoggerSettings settings, ELogType logType, string message, int maxTries = 3)
|
|
{
|
|
lock (_fileLock)
|
|
{
|
|
if (logger == null) return;
|
|
if (settings == null) return;
|
|
if (!settings.EnableFileLogging) return;
|
|
if (string.IsNullOrWhiteSpace(message)) return;
|
|
|
|
int tries = 0;
|
|
bool completed = false;
|
|
while (!completed)
|
|
{
|
|
try
|
|
{
|
|
if (logType == ELogType.CRITICAL)
|
|
{
|
|
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);
|
|
}
|
|
completed = true;
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
tries++;
|
|
Task.Delay(100);
|
|
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.SysLogServers == null || !settings.SysLogServers.Any())
|
|
{
|
|
settings.SysLogServers = new List<SyslogServer> { new SyslogServer("127.0.0.1", 514) };
|
|
}
|
|
|
|
byte[] data = Encoding.UTF8.GetBytes(message);
|
|
|
|
var sysLogServers = settings.SysLogServers.ToList();
|
|
foreach (SyslogServer server in sysLogServers)
|
|
{
|
|
lock (server.SendLock)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(server.Hostname))
|
|
{
|
|
Console.WriteLine("Server hostname not specified, skipping syslog server");
|
|
}
|
|
if (server.Port < 0)
|
|
{
|
|
Console.WriteLine("Server port must be zero or greater, skipping syslog server");
|
|
}
|
|
|
|
try
|
|
{
|
|
server.Udp.Send(data, data.Length);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |