Updated
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
|
||||
namespace EonaCat.Logger.Extensions
|
||||
@@ -12,11 +13,7 @@ namespace EonaCat.Logger.Extensions
|
||||
/// </summary>
|
||||
public static class FileLoggerFactoryExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds a file logger named 'File' to the factory.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="ILoggingBuilder"/> to use.</param>
|
||||
public static ILoggingBuilder AddEonaCatFileLogger(this ILoggingBuilder builder)
|
||||
private static ILoggingBuilder AddEonaCatFileLogger(this ILoggingBuilder builder)
|
||||
{
|
||||
builder.Services.AddSingleton<ILoggerProvider, FileLoggerProvider>();
|
||||
return builder;
|
||||
@@ -26,15 +23,39 @@ namespace EonaCat.Logger.Extensions
|
||||
/// Adds the EonaCat File Logger named 'EonaCatFileLogger' to the factory.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="ILoggingBuilder"/> to use.</param>
|
||||
/// <param name="filenamePrefix">Sets the filename prefix to use for log files</param>
|
||||
public static ILoggingBuilder AddEonaCatFileLogger(this ILoggingBuilder builder, string filenamePrefix)
|
||||
/// <param name="filenamePrefix">Sets the filename prefix to use for log files (optional)</param>
|
||||
/// <param name="fileLoggerOptions">the options for the fileLogger that needs to be used (optional)</param>
|
||||
public static ILoggingBuilder AddEonaCatFileLogger(this ILoggingBuilder builder, string filenamePrefix = null, FileLoggerOptions fileLoggerOptions = null)
|
||||
{
|
||||
builder.AddEonaCatFileLogger(options => options.FileNamePrefix = filenamePrefix);
|
||||
if (fileLoggerOptions == null)
|
||||
{
|
||||
fileLoggerOptions = new FileLoggerOptions();
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filenamePrefix))
|
||||
{
|
||||
fileLoggerOptions.FileNamePrefix = filenamePrefix;
|
||||
}
|
||||
builder.AddEonaCatFileLogger(options =>
|
||||
{
|
||||
options.FileNamePrefix = fileLoggerOptions.FileNamePrefix;
|
||||
options.FlushPeriod = fileLoggerOptions.FlushPeriod;
|
||||
options.RetainedFileCountLimit = fileLoggerOptions.RetainedFileCountLimit;
|
||||
options.MaxWriteTries = fileLoggerOptions.MaxWriteTries;
|
||||
options.FileSizeLimit = fileLoggerOptions.FileSizeLimit;
|
||||
options.LogDirectory = fileLoggerOptions.LogDirectory;
|
||||
options.BatchSize = fileLoggerOptions.BatchSize;
|
||||
options.FileSizeLimit = fileLoggerOptions.FileSizeLimit;
|
||||
options.IsEnabled = fileLoggerOptions.IsEnabled;
|
||||
options.MaxRolloverFiles = fileLoggerOptions.MaxRolloverFiles;
|
||||
}
|
||||
|
||||
);
|
||||
return builder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a file logger named 'File' to the factory.
|
||||
/// Adds the EonaCat File Logger named 'EonaCatFileLogger' to the factory.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="ILoggingBuilder"/> to use.</param>
|
||||
/// <param name="configure">Configure an instance of the <see cref="FileLoggerOptions" /> to set logging options</param>
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace EonaCat.Logger
|
||||
/// <summary>
|
||||
/// An <see cref="ILoggerProvider" /> that writes logs to a file
|
||||
/// </summary>
|
||||
[ProviderAlias("File")]
|
||||
[ProviderAlias("EonaCatFileLogger")]
|
||||
public class FileLoggerProvider : BatchingLoggerProvider
|
||||
{
|
||||
private readonly string _path;
|
||||
@@ -28,7 +28,9 @@ namespace EonaCat.Logger
|
||||
private readonly int _maxTries;
|
||||
private int _rollOverCount = 0;
|
||||
private static readonly object _writeLock = new object();
|
||||
private static readonly object _rollOverLock = new object();
|
||||
private string _logFile;
|
||||
private bool rollingOver;
|
||||
|
||||
/// <summary>
|
||||
/// The file to which log messages should be appended.
|
||||
@@ -87,27 +89,31 @@ namespace EonaCat.Logger
|
||||
{
|
||||
if (_rollOverCount < _maxRolloverFiles)
|
||||
{
|
||||
fileInfo.CopyTo(LogFile.Replace(".log", $"_{++_rollOverCount}.log"));
|
||||
var rollOverFile = LogFile.Replace(".log", $"_{++_rollOverCount}.log");
|
||||
if (File.Exists(rollOverFile))
|
||||
{
|
||||
File.Delete(rollOverFile);
|
||||
}
|
||||
fileInfo.CopyTo(rollOverFile);
|
||||
File.WriteAllText(LogFile, string.Empty);
|
||||
}
|
||||
else
|
||||
{
|
||||
bool areFilesDeleted = false;
|
||||
for (int i = 0; i < _rollOverCount; i++)
|
||||
lock (_rollOverLock)
|
||||
{
|
||||
File.Delete(LogFile.Replace(".log", $"_{i}.log"));
|
||||
areFilesDeleted = true;
|
||||
}
|
||||
|
||||
if (areFilesDeleted)
|
||||
{
|
||||
File.Move(LogFile.Replace(".log", $"_{_rollOverCount}.log"), LogFile.Replace(".log", $"_1.log"));
|
||||
_rollOverCount = 0;
|
||||
rollingOver = true;
|
||||
MoveRolloverLogFiles();
|
||||
rollingOver = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (rollingOver)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
lock (_writeLock)
|
||||
{
|
||||
int tries = 0;
|
||||
@@ -135,9 +141,9 @@ namespace EonaCat.Logger
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DeleteOldLogFiles();
|
||||
DeleteOldLogFiles();
|
||||
}
|
||||
}
|
||||
|
||||
private string GetFullName((int Year, int Month, int Day) group)
|
||||
@@ -158,6 +164,64 @@ namespace EonaCat.Logger
|
||||
return (message.Timestamp.Year, message.Timestamp.Month, message.Timestamp.Day);
|
||||
}
|
||||
|
||||
private static void MoveFile(string copyFromPath, string copyToPath)
|
||||
{
|
||||
var origin = new FileInfo(copyFromPath);
|
||||
origin.MoveTo(copyToPath);
|
||||
|
||||
var destination = new FileInfo(copyToPath);
|
||||
destination.CreationTime = origin.CreationTime;
|
||||
destination.LastWriteTime = origin.LastWriteTime;
|
||||
destination.LastAccessTime = origin.LastAccessTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rollover logFiles
|
||||
/// </summary>
|
||||
protected void MoveRolloverLogFiles()
|
||||
{
|
||||
if (_maxRolloverFiles > 0 && _rollOverCount >= 0)
|
||||
{
|
||||
if (_rollOverCount >= _maxRolloverFiles)
|
||||
{
|
||||
var maxRollover = _rollOverCount;
|
||||
bool hasPrefix = !string.IsNullOrWhiteSpace(_fileNamePrefix);
|
||||
IEnumerable<FileInfo> files;
|
||||
if (hasPrefix)
|
||||
{
|
||||
files = new DirectoryInfo(_path).GetFiles(_fileNamePrefix + "*").OrderBy(x => x.CreationTime);
|
||||
}
|
||||
else
|
||||
{
|
||||
files = new DirectoryInfo(_path).GetFiles("*").OrderBy(x => x.CreationTime);
|
||||
}
|
||||
|
||||
for (int i = files.Count() -1; i >= 0; i--)
|
||||
{
|
||||
var currentFile = files.ElementAt(i);
|
||||
if (i == 0)
|
||||
{
|
||||
// Temporary move first file
|
||||
var newFilename2 = Path.GetFileName(currentFile.FullName).Replace($".log", $"_{i + 1}.log");
|
||||
MoveFile(currentFile.FullName, $@"{Path.GetDirectoryName(currentFile.FullName)}\{newFilename2}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i == files.Count() - 1)
|
||||
{
|
||||
// Delete the last file
|
||||
File.Delete(currentFile.FullName);
|
||||
continue;
|
||||
}
|
||||
|
||||
var newFilename = Path.GetFileName(currentFile.FullName).Replace($"_{i}.log", $"_{i + 1}.log");
|
||||
MoveFile(currentFile.FullName, $@"{Path.GetDirectoryName(currentFile.FullName)}\{newFilename}");
|
||||
}
|
||||
_rollOverCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes old log files, keeping a number of files defined by <see cref="FileLoggerOptions.RetainedFileCountLimit" />
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using EonaCat.logger.Managers;
|
||||
using EonaCat.Logger.Managers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Text;
|
||||
@@ -10,11 +11,13 @@ namespace EonaCat.Logger.Internal
|
||||
|
||||
public class BatchingLogger : ILogger
|
||||
{
|
||||
private LoggerSettings _loggerSettings;
|
||||
private readonly BatchingLoggerProvider _provider;
|
||||
private readonly string _category;
|
||||
|
||||
public BatchingLogger(BatchingLoggerProvider loggerProvider, string categoryName)
|
||||
public BatchingLogger(BatchingLoggerProvider loggerProvider, string categoryName, LoggerSettings loggerSettings = null)
|
||||
{
|
||||
_loggerSettings = loggerSettings;
|
||||
_provider = loggerProvider;
|
||||
_category = categoryName;
|
||||
}
|
||||
@@ -32,9 +35,13 @@ namespace EonaCat.Logger.Internal
|
||||
public void Log<TState>(DateTimeOffset timestamp, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel)) return;
|
||||
|
||||
if (_loggerSettings == null)
|
||||
{
|
||||
_loggerSettings = new LoggerSettings();
|
||||
}
|
||||
|
||||
var message = LogHelper.FormatMessageWithHeader(new Managers.LoggerSettings(), logLevel.FromLogLevel(), formatter(state, exception)) + Environment.NewLine;
|
||||
|
||||
var message = LogHelper.FormatMessageWithHeader(_loggerSettings, logLevel.FromLogLevel(), formatter(state, exception)) + Environment.NewLine;
|
||||
if (exception != null)
|
||||
{
|
||||
message = exception.FormatExceptionToMessage() + Environment.NewLine;
|
||||
|
||||
@@ -7,9 +7,8 @@ namespace EonaCat.Logger.Internal
|
||||
|
||||
public class BatchingLoggerOptions
|
||||
{
|
||||
private int _batchSize = 32;
|
||||
private int _backgroundQueueSize;
|
||||
private TimeSpan _flushPeriod = TimeSpan.FromSeconds(1);
|
||||
private int _batchSize = 0;
|
||||
private TimeSpan _flushPeriod = TimeSpan.FromMilliseconds(100);
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the period after which logs will be flushed to the store.
|
||||
@@ -28,21 +27,6 @@ namespace EonaCat.Logger.Internal
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum size of the background log message queue or less than 1 for no limit.
|
||||
/// After maximum queue size is reached log event sink would start blocking.
|
||||
/// Defaults to <c>0</c>.
|
||||
/// </summary>
|
||||
public int BackgroundQueueSize
|
||||
{
|
||||
get => _backgroundQueueSize;
|
||||
|
||||
set
|
||||
{
|
||||
_backgroundQueueSize = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a maximum number of events to include in a single batch or less than 1 for no limit.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using EonaCat.Logger.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
@@ -15,10 +16,9 @@ namespace EonaCat.Logger.Internal
|
||||
{
|
||||
private readonly List<LogMessage> _currentBatch = new List<LogMessage>();
|
||||
private readonly TimeSpan _interval;
|
||||
private readonly int _queueSize;
|
||||
private readonly int _batchSize;
|
||||
|
||||
private BlockingCollection<LogMessage> _messageQueue;
|
||||
private ConcurrentQueue<LogMessage> _messageQueue;
|
||||
private Task _outputTask;
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
|
||||
@@ -26,11 +26,6 @@ namespace EonaCat.Logger.Internal
|
||||
{
|
||||
BatchingLoggerOptions loggerOptions = options.Value;
|
||||
|
||||
if (loggerOptions.BatchSize <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(loggerOptions.BatchSize), $"{nameof(loggerOptions.BatchSize)} must be a positive number.");
|
||||
}
|
||||
|
||||
if (loggerOptions.FlushPeriod <= TimeSpan.Zero)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(loggerOptions.FlushPeriod), $"{nameof(loggerOptions.FlushPeriod)} must be longer than zero.");
|
||||
@@ -38,7 +33,6 @@ namespace EonaCat.Logger.Internal
|
||||
|
||||
_interval = loggerOptions.FlushPeriod;
|
||||
_batchSize = loggerOptions.BatchSize;
|
||||
_queueSize = loggerOptions.BackgroundQueueSize;
|
||||
|
||||
Start();
|
||||
}
|
||||
@@ -47,11 +41,12 @@ namespace EonaCat.Logger.Internal
|
||||
|
||||
private async Task ProcessLogQueue(object state)
|
||||
{
|
||||
await WriteMessagesAsync(new List<LogMessage> { new LogMessage { Message = $"[{DllInfo.ApplicationName}] {DllInfo.ApplicationName} started.{Environment.NewLine}", Timestamp = DateTimeOffset.Now } }, _cancellationTokenSource.Token);
|
||||
while (!_cancellationTokenSource.IsCancellationRequested)
|
||||
{
|
||||
int limit = _batchSize <= 0 ? int.MaxValue : _batchSize;
|
||||
|
||||
while (limit > 0 && _messageQueue.TryTake(out LogMessage message))
|
||||
while (limit > 0 && _messageQueue.TryDequeue(out LogMessage message))
|
||||
{
|
||||
_currentBatch.Add(message);
|
||||
limit--;
|
||||
@@ -73,6 +68,7 @@ namespace EonaCat.Logger.Internal
|
||||
|
||||
await IntervalAsync(_interval, _cancellationTokenSource.Token);
|
||||
}
|
||||
await WriteMessagesAsync(new List<LogMessage> { new LogMessage { Message = $"[{DllInfo.ApplicationName}] {DllInfo.ApplicationName} stopped.{Environment.NewLine}", Timestamp = DateTimeOffset.Now } }, _cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
protected virtual Task IntervalAsync(TimeSpan interval, CancellationToken cancellationToken)
|
||||
@@ -82,24 +78,12 @@ namespace EonaCat.Logger.Internal
|
||||
|
||||
internal void AddMessage(DateTimeOffset timestamp, string message)
|
||||
{
|
||||
if (!_messageQueue.IsAddingCompleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
_messageQueue.Add(new LogMessage { Message = message, Timestamp = timestamp }, _cancellationTokenSource.Token);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// cancellation token canceled or CompleteAdding called
|
||||
}
|
||||
}
|
||||
_messageQueue.Enqueue(new LogMessage { Message = message, Timestamp = timestamp });
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_messageQueue = _queueSize == 0 ?
|
||||
new BlockingCollection<LogMessage>(new ConcurrentQueue<LogMessage>()) :
|
||||
new BlockingCollection<LogMessage>(new ConcurrentQueue<LogMessage>(), _queueSize);
|
||||
_messageQueue = new ConcurrentQueue<LogMessage>();
|
||||
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
_outputTask = Task.Factory.StartNew(
|
||||
@@ -111,7 +95,6 @@ namespace EonaCat.Logger.Internal
|
||||
private void Stop()
|
||||
{
|
||||
_cancellationTokenSource.Cancel();
|
||||
_messageQueue.CompleteAdding();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user