322 lines
10 KiB
C#
322 lines
10 KiB
C#
using EonaCat.Logger.Exceptions;
|
|
using EonaCat.Logger.Helpers;
|
|
using EonaCat.Logger.Syslog;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using EonaCat.Logger.EonaCatCoreLogger;
|
|
using EonaCat.Logger.EonaCatCoreLogger.Extensions;
|
|
using EonaCat.Logger.EonaCatCoreLogger.Models;
|
|
|
|
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 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 bool IsRunning { get; private set; }
|
|
|
|
public StreamWriter Output { get; private set; }
|
|
|
|
public string CategoryName { get; set; }
|
|
|
|
public readonly string Id;
|
|
|
|
private bool _disposed;
|
|
private static LogManager _instance;
|
|
private LoggerSettings _settings;
|
|
private readonly 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)
|
|
{
|
|
if (_disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (disposing)
|
|
{
|
|
StopLogging();
|
|
_tokenSource.Cancel();
|
|
}
|
|
|
|
_disposed = true;
|
|
}
|
|
|
|
private void StartNewLog()
|
|
{
|
|
if (_tokenSource.IsCancellationRequested)
|
|
{
|
|
return;
|
|
}
|
|
|
|
DateTime now = DateTime.Now;
|
|
|
|
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 serviceProvider = serviceCollection.BuildServiceProvider();
|
|
LoggerProvider = serviceProvider.GetService<ILoggerProvider>();
|
|
LoggerFactory = serviceProvider.GetService<ILoggerFactory>();
|
|
|
|
CategoryName = CategoryName ?? string.Empty;
|
|
Logger = LoggerFactory.CreateLogger(CategoryName);
|
|
|
|
if (!Directory.Exists(Settings.FileLoggerOptions.LogDirectory))
|
|
{
|
|
Directory.CreateDirectory(Settings.FileLoggerOptions.LogDirectory);
|
|
}
|
|
|
|
_logDate = now;
|
|
|
|
Write(now, $"{DllInfo.ApplicationName} started.");
|
|
}
|
|
|
|
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;
|
|
|
|
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, dateTime);
|
|
|
|
if (writeToConsole == null)
|
|
{
|
|
writeToConsole = _settings.EnableConsole;
|
|
}
|
|
|
|
LogHelper.SendConsole(_settings, logType, fullMessage, writeToConsole == true);
|
|
|
|
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
|
|
};
|
|
|
|
if (Settings != null)
|
|
{
|
|
logMessage.Origin = string.IsNullOrWhiteSpace(Settings.LogOrigin) ? "LogManager" : Settings.LogOrigin;
|
|
Settings?.OnLogEvent(logMessage);
|
|
}
|
|
|
|
Settings?.OnLogEvent(logMessage);
|
|
}
|
|
|
|
public void Reset() => Settings?.ResetLogEvent();
|
|
|
|
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.");
|
|
|
|
settings.SysLogServers = new List<SyslogServer>
|
|
{
|
|
new SyslogServer(serverIp, serverPort)
|
|
};
|
|
|
|
Id = id;
|
|
Settings = settings;
|
|
SetupLogManager();
|
|
}
|
|
|
|
public LogManager(LoggerSettings settings, string id = "EonaCatLogger")
|
|
{
|
|
Id = id;
|
|
Settings = settings;
|
|
SetupFileLogger(settings, null, true);
|
|
SetupLogManager();
|
|
}
|
|
|
|
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 (logFolder != null)
|
|
{
|
|
Settings.FileLoggerOptions.LogDirectory = logFolder;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(Settings.FileLoggerOptions.FileNamePrefix))
|
|
{
|
|
if (defaultPrefix)
|
|
{
|
|
Settings.FileLoggerOptions.FileNamePrefix = "EonaCat";
|
|
}
|
|
else
|
|
{
|
|
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, _token);
|
|
}
|
|
|
|
public LogManager(string logFolder = null, bool defaultPrefix = true)
|
|
{
|
|
SetupFileLogger(null, logFolder, defaultPrefix);
|
|
SetupLogManager();
|
|
}
|
|
|
|
public void Write(Exception exception, string module = null, string method = null, bool criticalException = false, bool? writeToConsole = null)
|
|
{
|
|
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;
|
|
|
|
if (!IsRunning)
|
|
{
|
|
StartNewLog();
|
|
}
|
|
|
|
Write(now, message, logType, writeToConsole);
|
|
}
|
|
|
|
public void DeleteCurrentLogFile()
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(CurrentLogFile))
|
|
{
|
|
File.Delete(CurrentLogFile);
|
|
}
|
|
}
|
|
|
|
void IDisposable.Dispose()
|
|
{
|
|
Dispose(true);
|
|
}
|
|
}
|
|
} |