using InnovEnergy.Lib.Utils; using Microsoft.Extensions.Logging; namespace InnovEnergy.App.GrowattCommunication.DataLogging; public class CustomLogger : ILogger { private readonly String _LogFilePath; //private readonly Int64 _maxFileSizeBytes; private readonly Int32 _MaxLogFileCount; private Int64 _CurrentFileSizeBytes; public CustomLogger(String logFilePath, Int32 maxLogFileCount) { _LogFilePath = logFilePath; _MaxLogFileCount = maxLogFileCount; _CurrentFileSizeBytes = File.Exists(logFilePath) ? new FileInfo(logFilePath).Length : 0; } public IDisposable? BeginScope(TState state) where TState : notnull => throw new NotImplementedException(); public Boolean IsEnabled(LogLevel logLevel) => true; // Enable logging for all levels public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { var logMessage = formatter(state, exception!); // Check the log file count and delete the oldest file if necessary var logFileDir = Path.GetDirectoryName(_LogFilePath)!; var logFileExt = Path.GetExtension(_LogFilePath); var logFileBaseName = Path.GetFileNameWithoutExtension(_LogFilePath); var logFiles = Directory .GetFiles(logFileDir, $"{logFileBaseName}_*{logFileExt}") .OrderBy(file => file) .ToList(); if (logFiles.Count >= _MaxLogFileCount) { File.Delete(logFiles.First()); } var roundedUnixTimestamp = DateTime.Now.ToUnixTime() % 2 == 0 ? DateTime.Now.ToUnixTime() : DateTime.Now.ToUnixTime() + 1; var timestamp = "Timestamp;" + roundedUnixTimestamp + Environment.NewLine; var logFileBackupPath = Path.Combine(logFileDir, $"{logFileBaseName}_{DateTime.Now.ToUnixTime()}{logFileExt}"); File.AppendAllText(logFileBackupPath, timestamp + logMessage + Environment.NewLine); } }