Added sysLogServer functionality
This commit is contained in:
292
EonaCat.Logger/Managers/LogHelper.cs
Normal file
292
EonaCat.Logger/Managers/LogHelper.cs
Normal file
@@ -0,0 +1,292 @@
|
||||
using EonaCat.Logger;
|
||||
using EonaCat.Logger.Managers;
|
||||
using EonaCat.Logger.Syslog;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections;
|
||||
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>
|
||||
/// <returns></returns>
|
||||
public static string FormatMessageWithHeader(LoggerSettings settings, ELogType logType, string currentMessage)
|
||||
{
|
||||
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.Now.ToUniversalTime().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 = "[EonaCatLogger]" + " " + header + " " + currentMessage;
|
||||
return fullMessage;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (settings == null) return;
|
||||
if (!settings.EnableConsole) 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;
|
||||
//logger.LogInformation(message);
|
||||
|
||||
int tries = 0;
|
||||
bool completed = false;
|
||||
while (!completed)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.IO.StreamWriter file = new System.IO.StreamWriter($"{settings.FileLoggerOptions.LogDirectory}{Path.DirectorySeparatorChar}{settings.FileLoggerOptions.FileNamePrefix}_{DateTime.Now.ToString("yyyyMMdd")}.log", true);
|
||||
file.Write(message + Environment.NewLine);
|
||||
file.Close();
|
||||
completed = true;
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
tries++;
|
||||
Task.Delay(100);
|
||||
if (tries >= maxTries)
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void SendToSysLogServers(LoggerSettings settings, string message)
|
||||
{
|
||||
if (settings == null) return;
|
||||
if (!settings.SendToSyslogServers) return;
|
||||
if (settings.SysLogServers == null) return;
|
||||
if (!settings.SysLogServers.Any()) return;
|
||||
if (string.IsNullOrWhiteSpace(message)) return;
|
||||
|
||||
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)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user