Added sysLogServer functionality
This commit is contained in:
@@ -1,13 +1,17 @@
|
||||
using EonaCat.Extensions;
|
||||
using EonaCat.logger.Managers;
|
||||
using EonaCat.Logger.Exceptions;
|
||||
using EonaCat.Logger.Extensions;
|
||||
using EonaCat.Logger.Helpers;
|
||||
using EonaCat.Logger.Syslog;
|
||||
using EonaCatLogger.EonaCatCoreLogger.Models;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -16,11 +20,15 @@ namespace EonaCat.Logger.Managers
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||
|
||||
public class LogManager : IDisposable
|
||||
public partial class LogManager : ILogManager, IDisposable
|
||||
{
|
||||
private readonly object _batton = new object();
|
||||
private DateTime _logDate;
|
||||
public event LogDelegate OnLog;
|
||||
public delegate void LogDelegate(LogManager logger, ELogType logLevel, EonaCatLogMessage message);
|
||||
|
||||
|
||||
public ELogType LogType;
|
||||
private ILoggerProvider LoggerProvider { get; set; }
|
||||
private ILoggerFactory LoggerFactory { get; set; }
|
||||
private ILogger Logger { get; set; }
|
||||
@@ -29,13 +37,50 @@ namespace EonaCat.Logger.Managers
|
||||
public bool IsRunning { get; private set; }
|
||||
|
||||
public StreamWriter Output { get; private set; }
|
||||
public string LogFolderPath { get; set; } = "logs";
|
||||
public FileLoggerOptions FileLoggerOptions { get; private set; }
|
||||
public int FileSizeLimit { get; set; } = 200 * 1024 * 1024;
|
||||
|
||||
public string CategoryName { get; set; }
|
||||
private LogManager Instance { get; set; }
|
||||
|
||||
public readonly string Id;
|
||||
|
||||
private bool _disposed;
|
||||
private static LogManager _instance;
|
||||
private LoggerSettings _settings;
|
||||
private CancellationTokenSource _TokenSource = new CancellationTokenSource();
|
||||
private CancellationToken _Token;
|
||||
|
||||
/// <summary>
|
||||
/// Default Logger Instance with it's default configuration
|
||||
/// </summary>
|
||||
public static LogManager Instance => InstanceInit();
|
||||
|
||||
/// <summary>
|
||||
/// Logging settings.
|
||||
/// </summary>
|
||||
public LoggerSettings Settings
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_settings == null)
|
||||
{
|
||||
_settings = new LoggerSettings();
|
||||
}
|
||||
return _settings;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
_settings = value;
|
||||
}
|
||||
}
|
||||
|
||||
private static LogManager InstanceInit()
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
_instance = new LogManager(null, id: "EonaCat");
|
||||
}
|
||||
return _instance;
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
@@ -49,47 +94,20 @@ namespace EonaCat.Logger.Managers
|
||||
if (disposing)
|
||||
{
|
||||
StopLogging();
|
||||
_TokenSource.Cancel();
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
public static async Task DownloadLogAsync(HttpResponse response, string logFile, long limit)
|
||||
{
|
||||
using (FileStream fileStream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
response.ContentType = "text/plain";
|
||||
response.Headers.Add("Content-Disposition", "attachment;filename=" + Path.GetFileName(logFile));
|
||||
|
||||
if (limit > fileStream.Length)
|
||||
{
|
||||
limit = fileStream.Length;
|
||||
}
|
||||
|
||||
using (OffsetStream offsetStream = new OffsetStream(fileStream, 0, limit))
|
||||
{
|
||||
using (Stream stream = response.Body)
|
||||
{
|
||||
offsetStream.CopyTo(stream);
|
||||
|
||||
if (fileStream.Length > limit)
|
||||
{
|
||||
byte[] buffer = Encoding.UTF8.GetBytes("####___EonaCatLogger_TRUNCATED___####");
|
||||
await stream.WriteAsync(buffer, 0, buffer.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void StartNewLog()
|
||||
{
|
||||
if (_TokenSource.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DateTime now = DateTime.Now;
|
||||
|
||||
if (IsRunning && now.Date > _logDate.Date)
|
||||
@@ -99,143 +117,157 @@ namespace EonaCat.Logger.Managers
|
||||
IsRunning = true;
|
||||
|
||||
IServiceCollection serviceCollection = new ServiceCollection();
|
||||
CreateDefaultFileLoggerOptions();
|
||||
|
||||
serviceCollection.AddLogging(builder => builder.AddFile(configuration =>
|
||||
serviceCollection.AddLogging(builder => builder.AddEonaCatFileLogger(configuration =>
|
||||
{
|
||||
configuration.BackgroundQueueSize = FileLoggerOptions.BackgroundQueueSize;
|
||||
configuration.BatchSize = FileLoggerOptions.BatchSize;
|
||||
configuration.FileNamePrefix = FileLoggerOptions.FileNamePrefix;
|
||||
configuration.FileSizeLimit = FileLoggerOptions.FileSizeLimit;
|
||||
configuration.FlushPeriod = FileLoggerOptions.FlushPeriod;
|
||||
configuration.IsEnabled = FileLoggerOptions.IsEnabled;
|
||||
configuration.LogDirectory = FileLoggerOptions.LogDirectory;
|
||||
configuration.RetainedFileCountLimit = FileLoggerOptions.RetainedFileCountLimit;
|
||||
configuration = Settings.FileLoggerOptions;
|
||||
}));
|
||||
|
||||
var serviceProvider = serviceCollection.BuildServiceProvider();
|
||||
LoggerProvider = serviceProvider.GetService<ILoggerProvider>();
|
||||
LoggerFactory = serviceProvider.GetService<ILoggerFactory>();
|
||||
|
||||
CategoryName = CategoryName ?? string.Empty;
|
||||
Logger = LoggerFactory.CreateLogger(CategoryName);
|
||||
|
||||
if (!Directory.Exists(FileLoggerOptions.LogDirectory))
|
||||
if (!Directory.Exists(Settings.FileLoggerOptions.LogDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(FileLoggerOptions.LogDirectory);
|
||||
Directory.CreateDirectory(Settings.FileLoggerOptions.LogDirectory);
|
||||
}
|
||||
|
||||
_logDate = now;
|
||||
|
||||
Write(now, "EonaCatLogger started.");
|
||||
Write(now, $"{DllInfo.ApplicationName} started.");
|
||||
}
|
||||
|
||||
private void CreateDefaultFileLoggerOptions()
|
||||
public void Assert(bool condition, string message)
|
||||
{
|
||||
if (FileLoggerOptions == null)
|
||||
if (!condition)
|
||||
{
|
||||
FileLoggerOptions = new FileLoggerOptions
|
||||
{
|
||||
LogDirectory = LogFolderPath,
|
||||
FileSizeLimit = FileSizeLimit
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteToFile(EonaCatLogMessage EonaCatLogMessage)
|
||||
{
|
||||
if (EonaCatLogMessage.LogType == ELogType.CRITICAL)
|
||||
{
|
||||
Instance.Logger.LogCritical(EonaCatLogMessage.Message);
|
||||
}
|
||||
else if (EonaCatLogMessage.LogType == ELogType.DEBUG)
|
||||
{
|
||||
Instance.Logger.LogDebug(EonaCatLogMessage.Message);
|
||||
}
|
||||
else if (EonaCatLogMessage.LogType == ELogType.ERROR)
|
||||
{
|
||||
Instance.Logger.LogError(EonaCatLogMessage.Message);
|
||||
}
|
||||
else if (EonaCatLogMessage.LogType == ELogType.INFO)
|
||||
{
|
||||
Instance.Logger.LogInformation(EonaCatLogMessage.Message);
|
||||
}
|
||||
else if (EonaCatLogMessage.LogType == ELogType.TRACE)
|
||||
{
|
||||
Instance.Logger.LogTrace(EonaCatLogMessage.Message);
|
||||
}
|
||||
else if (EonaCatLogMessage.LogType == ELogType.TRAFFIC)
|
||||
{
|
||||
Instance.Logger.LogTrace($"[TRAFFIC] {EonaCatLogMessage.Message}");
|
||||
}
|
||||
else if (EonaCatLogMessage.LogType == ELogType.WARNING)
|
||||
{
|
||||
Instance.Logger.LogWarning(EonaCatLogMessage.Message);
|
||||
throw new EonaCatLoggerAssertionException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void Write(DateTime dateTime, string message, ELogType logType = ELogType.INFO)
|
||||
{
|
||||
var EonaCatMessage = new EonaCatLogMessage { DateTime = dateTime, Message = message, LogType = logType };
|
||||
WriteToFile(EonaCatMessage);
|
||||
if (string.IsNullOrWhiteSpace(message)) return;
|
||||
if (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;
|
||||
}
|
||||
|
||||
var fullMessage = LogHelper.FormatMessageWithHeader(_settings, logType, currentMessage);
|
||||
|
||||
LogHelper.SendConsole(_settings, logType, fullMessage);
|
||||
|
||||
LogHelper.SendFile(Logger, _settings, logType, fullMessage);
|
||||
|
||||
LogHelper.SendToSysLogServers(_settings, fullMessage);
|
||||
|
||||
if (!string.IsNullOrEmpty(remainder))
|
||||
{
|
||||
Write(dateTime, remainder, logType);
|
||||
}
|
||||
|
||||
var EonaCatMessage = new EonaCatLogMessage { DateTime = dateTime, Message = currentMessage, LogType = logType };
|
||||
OnLog?.Invoke(this, logType, EonaCatMessage);
|
||||
}
|
||||
|
||||
private LogManager()
|
||||
{
|
||||
// Do nothing
|
||||
}
|
||||
public void Reset() => OnLog = null;
|
||||
|
||||
public LogManager(FileLoggerOptions fileLoggerOptions)
|
||||
public LogManager(LoggerSettings settings, string serverIp, int serverPort, string id = "EonaCatLogger")
|
||||
{
|
||||
FileLoggerOptions = fileLoggerOptions;
|
||||
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<SyslogServer>();
|
||||
settings.SysLogServers.Add(new SyslogServer(serverIp, serverPort));
|
||||
|
||||
Id = id;
|
||||
Settings = settings;
|
||||
SetupLogManager();
|
||||
}
|
||||
|
||||
private void SetupLogManager()
|
||||
public LogManager(LoggerSettings settings, string id = "EonaCatLogger")
|
||||
{
|
||||
AppDomain.CurrentDomain.ProcessExit += ProcessExit;
|
||||
|
||||
Instance = this;
|
||||
|
||||
_logDate = DateTime.Now;
|
||||
|
||||
StartNewLog();
|
||||
Id = id;
|
||||
Settings = settings;
|
||||
SetupFileLogger(settings, null, true);
|
||||
SetupLogManager();
|
||||
}
|
||||
|
||||
private void ProcessExit(object sender, EventArgs e)
|
||||
private void SetupFileLogger(LoggerSettings settings = null, string logFolder = null, bool defaultPrefix = true)
|
||||
{
|
||||
Instance?.StopLogging();
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
if (settings == null)
|
||||
{
|
||||
// Create default loggingSettings
|
||||
Settings = settings;
|
||||
settings = Settings;
|
||||
}
|
||||
|
||||
private void StopLogging()
|
||||
{
|
||||
Write(DateTime.Now, "EonaCatLogger stopped.");
|
||||
IsRunning = false;
|
||||
}
|
||||
|
||||
public LogManager(string logFolder = null, bool defaultPrefix = true)
|
||||
{
|
||||
CreateDefaultFileLoggerOptions();
|
||||
if (!settings.EnableFileLogging) return;
|
||||
|
||||
if (logFolder != null)
|
||||
{
|
||||
FileLoggerOptions.LogDirectory = logFolder;
|
||||
Settings.FileLoggerOptions.LogDirectory = logFolder;
|
||||
}
|
||||
|
||||
if (defaultPrefix)
|
||||
{
|
||||
FileLoggerOptions.FileNamePrefix = "EonaCat";
|
||||
Settings.FileLoggerOptions.FileNamePrefix = "EonaCat";
|
||||
}
|
||||
else
|
||||
{
|
||||
FileLoggerOptions.FileNamePrefix = string.Empty;
|
||||
Settings.FileLoggerOptions.FileNamePrefix = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetupLogManager()
|
||||
{
|
||||
_Token = _TokenSource.Token;
|
||||
AppDomain.CurrentDomain.ProcessExit += ProcessExit;
|
||||
|
||||
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
|
||||
|
||||
_logDate = DateTime.Now;
|
||||
}
|
||||
|
||||
void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
private void ProcessExit(object sender, EventArgs e)
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
private void StopLogging()
|
||||
{
|
||||
IsRunning = false;
|
||||
Write(DateTime.Now, $"{DllInfo.ApplicationName} stopped.");
|
||||
Task.Delay(500);
|
||||
}
|
||||
|
||||
public LogManager(string logFolder = null, bool defaultPrefix = true)
|
||||
{
|
||||
SetupFileLogger(null, logFolder, defaultPrefix);
|
||||
SetupLogManager();
|
||||
}
|
||||
|
||||
public void Write(Exception exception)
|
||||
public void Write(Exception exception, string module = null, string method = null, bool criticalException = false)
|
||||
{
|
||||
Write(exception.ToString());
|
||||
if (exception != null) return;
|
||||
Write(exception.FormatExceptionToMessage(module, method), criticalException ? ELogType.CRITICAL : ELogType.ERROR);
|
||||
}
|
||||
|
||||
public void Write(string message, ELogType logType = ELogType.INFO, ELogType? logLevel = null)
|
||||
@@ -256,7 +288,7 @@ namespace EonaCat.Logger.Managers
|
||||
StartNewLog();
|
||||
}
|
||||
|
||||
Write(now, $"{DllInfo.ApplicationName}: {message}", logType);
|
||||
Write(now, message, logType);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -269,8 +301,12 @@ namespace EonaCat.Logger.Managers
|
||||
{
|
||||
File.Delete(CurrentLogFile);
|
||||
}
|
||||
StartNewLog();
|
||||
}
|
||||
}
|
||||
|
||||
void IDisposable.Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user