2023-09-14 12:20:30 +00:00
|
|
|
using InnovEnergy.Lib.Utils;
|
2023-06-13 11:01:48 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
namespace InnovEnergy.App.SaliMax;
|
|
|
|
|
2023-08-16 13:38:46 +00:00
|
|
|
public class CustomLogger : ILogger
|
2023-06-13 11:01:48 +00:00
|
|
|
{
|
2024-06-20 10:02:06 +00:00
|
|
|
private readonly String _logFilePath;
|
|
|
|
//private readonly Int64 _maxFileSizeBytes;
|
|
|
|
private readonly Int32 _maxLogFileCount;
|
|
|
|
private Int64 _currentFileSizeBytes;
|
2023-08-16 13:38:46 +00:00
|
|
|
|
2024-06-20 10:02:06 +00:00
|
|
|
public CustomLogger(String logFilePath, Int32 maxLogFileCount)
|
2023-08-16 13:38:46 +00:00
|
|
|
{
|
2024-06-20 10:02:06 +00:00
|
|
|
_logFilePath = logFilePath;
|
|
|
|
_maxLogFileCount = maxLogFileCount;
|
|
|
|
_currentFileSizeBytes = File.Exists(logFilePath) ? new FileInfo(logFilePath).Length : 0;
|
2023-08-16 13:38:46 +00:00
|
|
|
}
|
2023-06-13 11:01:48 +00:00
|
|
|
|
2023-08-16 13:11:37 +00:00
|
|
|
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => throw new NotImplementedException();
|
2023-06-13 11:01:48 +00:00
|
|
|
|
2023-08-16 13:11:37 +00:00
|
|
|
public Boolean IsEnabled(LogLevel logLevel) => true; // Enable logging for all levels
|
2023-06-13 11:01:48 +00:00
|
|
|
|
2023-08-16 13:38:46 +00:00
|
|
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception, String> formatter)
|
2023-06-13 11:01:48 +00:00
|
|
|
{
|
|
|
|
var logMessage = formatter(state, exception!);
|
2023-07-10 08:22:09 +00:00
|
|
|
|
2023-06-13 11:01:48 +00:00
|
|
|
// Check the log file count and delete the oldest file if necessary
|
2024-06-20 10:02:06 +00:00
|
|
|
var logFileDir = Path.GetDirectoryName(_logFilePath)!;
|
|
|
|
var logFileExt = Path.GetExtension(_logFilePath);
|
|
|
|
var logFileBaseName = Path.GetFileNameWithoutExtension(_logFilePath);
|
|
|
|
|
2023-07-04 09:18:07 +00:00
|
|
|
var logFiles = Directory
|
2024-06-20 10:02:06 +00:00
|
|
|
.GetFiles(logFileDir, $"{logFileBaseName}_*{logFileExt}")
|
|
|
|
.OrderBy(file => file)
|
|
|
|
.ToList();
|
2023-06-13 11:01:48 +00:00
|
|
|
|
2024-06-20 10:02:06 +00:00
|
|
|
if (logFiles.Count >= _maxLogFileCount)
|
|
|
|
{
|
2023-06-13 11:01:48 +00:00
|
|
|
File.Delete(logFiles.First());
|
2024-06-20 10:02:06 +00:00
|
|
|
}
|
2023-06-13 11:01:48 +00:00
|
|
|
|
2024-06-21 08:59:35 +00:00
|
|
|
var timestamp = "Timestamp;" + DateTime.Now.ToUnixTime() + Environment.NewLine;
|
2024-06-20 10:02:06 +00:00
|
|
|
|
2023-09-14 12:20:30 +00:00
|
|
|
var logFileBackupPath = Path.Combine(logFileDir, $"{logFileBaseName}_{DateTime.Now.ToUnixTime()}{logFileExt}");
|
2024-06-20 10:02:06 +00:00
|
|
|
File.AppendAllText(logFileBackupPath, timestamp + logMessage + Environment.NewLine);
|
2023-06-13 11:01:48 +00:00
|
|
|
}
|
|
|
|
}
|