Initial version

This commit is contained in:
2022-09-19 09:07:51 +02:00
parent 12150155da
commit 7783dc07e1
19 changed files with 1318 additions and 1 deletions

View File

@@ -0,0 +1,276 @@
using EonaCat.Extensions;
using EonaCat.Logger.Extensions;
using EonaCat.Logger.Helpers;
using EonaCatLogger.EonaCatCoreLogger.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
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
{
private readonly object _batton = new object();
private DateTime _logDate;
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 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; }
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
lock (this)
{
if (_disposed)
{
return;
}
if (disposing)
{
StopLogging();
}
_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()
{
DateTime now = DateTime.Now;
if (IsRunning && now.Date > _logDate.Date)
{
StopLogging();
}
IsRunning = true;
IServiceCollection serviceCollection = new ServiceCollection();
CreateDefaultFileLoggerOptions();
serviceCollection.AddLogging(builder => builder.AddFile(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;
}));
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))
{
Directory.CreateDirectory(FileLoggerOptions.LogDirectory);
}
_logDate = now;
Write(now, "EonaCatLogger started.");
}
private void CreateDefaultFileLoggerOptions()
{
if (FileLoggerOptions == null)
{
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);
}
}
private void Write(DateTime dateTime, string message, ELogType logType = ELogType.INFO)
{
var EonaCatMessage = new EonaCatLogMessage { DateTime = dateTime, Message = message, LogType = logType };
WriteToFile(EonaCatMessage);
}
private LogManager()
{
// Do nothing
}
public LogManager(FileLoggerOptions fileLoggerOptions)
{
FileLoggerOptions = fileLoggerOptions;
SetupLogManager();
}
private void SetupLogManager()
{
AppDomain.CurrentDomain.ProcessExit += ProcessExit;
Instance = this;
_logDate = DateTime.Now;
StartNewLog();
}
private void ProcessExit(object sender, EventArgs e)
{
Instance?.StopLogging();
Thread.Sleep(1000);
}
private void StopLogging()
{
Write(DateTime.Now, "EonaCatLogger stopped.");
IsRunning = false;
}
public LogManager(string logFolder = null, bool defaultPrefix = true)
{
CreateDefaultFileLoggerOptions();
if (logFolder != null)
{
FileLoggerOptions.LogDirectory = logFolder;
}
if (defaultPrefix)
{
FileLoggerOptions.FileNamePrefix = "EonaCat";
}
else
{
FileLoggerOptions.FileNamePrefix = string.Empty;
}
SetupLogManager();
}
public void Write(Exception exception)
{
Write(exception.ToString());
}
public void Write(string message, ELogType logType = ELogType.INFO, ELogType? logLevel = null)
{
lock (_batton)
{
if (logLevel == null)
{
logLevel = DllInfo.LogLevel;
}
if (logType == ELogType.CRITICAL || logLevel.GetValueOrDefault() <= logType)
{
DateTime now = DateTime.Now;
if (!IsRunning)
{
StartNewLog();
}
Write(now, $"{DllInfo.ApplicationName}: {message}", logType);
}
}
}
public void DeleteCurrentLogFile()
{
lock (this)
{
if (!string.IsNullOrWhiteSpace(CurrentLogFile))
{
File.Delete(CurrentLogFile);
}
StartNewLog();
}
}
}
}