Innovenergy_trunk/csharp/App/SaliMax/src/Logfile.cs

68 lines
2.3 KiB
C#
Raw Normal View History

2023-06-13 11:01:48 +00:00
using InnovEnergy.Lib.Time.Unix;
using Microsoft.Extensions.Logging;
namespace InnovEnergy.App.SaliMax;
public class CustomLogger : ILogger
{
private readonly String _logFilePath;
private readonly Int64 _maxFileSizeBytes;
private readonly Int32 _maxLogFileCount;
private Int64 _currentFileSizeBytes;
public CustomLogger(String logFilePath, Int64 maxFileSizeBytes, Int32 maxLogFileCount)
{
_logFilePath = logFilePath;
_maxFileSizeBytes = maxFileSizeBytes;
_maxLogFileCount = maxLogFileCount;
_currentFileSizeBytes = File.Exists(logFilePath) ? new FileInfo(logFilePath).Length : 0;
}
public IDisposable BeginScope<TState>(TState state)
{
throw new NotImplementedException();
}
public Boolean IsEnabled(LogLevel logLevel)
{
return true; // Enable logging for all levels
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception, String> formatter)
{
var logMessage = formatter(state, exception!);
// Check the file size and rotate the log file if necessary
if (_currentFileSizeBytes + logMessage.Length >= _maxFileSizeBytes)
{
RotateLogFile();
_currentFileSizeBytes = 0;
}
// Write the log message to the file
File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
_currentFileSizeBytes += logMessage.Length;
}
private void RotateLogFile()
{
// 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());
}
// Rename the current log file with a timestamp
var logFileBackupPath = Path.Combine(logFileDir, $"{logFileBaseName}_{UnixTime.Now}{logFileExt}");
File.Move(_logFilePath, logFileBackupPath);
}
}