2023-05-20 21:47:54 +02:00
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace Logging;
|
|
|
|
|
|
|
|
|
|
public class FileLogger : LoggerBase
|
|
|
|
|
{
|
2023-09-05 20:02:12 +02:00
|
|
|
|
internal string logFilePath { get; }
|
2023-05-21 15:33:01 +02:00
|
|
|
|
private const int MaxNumberOfLogFiles = 5;
|
2023-05-20 21:47:54 +02:00
|
|
|
|
|
2023-07-16 17:33:15 +02:00
|
|
|
|
public FileLogger(string logFilePath, Encoding? encoding = null) : base (encoding)
|
2023-05-20 21:47:54 +02:00
|
|
|
|
{
|
|
|
|
|
this.logFilePath = logFilePath;
|
2023-09-08 19:28:44 +02:00
|
|
|
|
|
|
|
|
|
DirectoryInfo dir = Directory.CreateDirectory(new FileInfo(logFilePath).DirectoryName!);
|
2023-05-21 15:33:01 +02:00
|
|
|
|
|
|
|
|
|
//Remove oldest logfile if more than MaxNumberOfLogFiles
|
2023-09-08 19:28:44 +02:00
|
|
|
|
for (int fileCount = dir.EnumerateFiles().Count(); fileCount > MaxNumberOfLogFiles - 1; fileCount--) //-1 because we create own logfile later
|
|
|
|
|
File.Delete(dir.EnumerateFiles().MinBy(file => file.LastWriteTime)!.FullName);
|
2023-05-20 21:47:54 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override void Write(LogMessage logMessage)
|
|
|
|
|
{
|
2023-05-20 22:56:05 +02:00
|
|
|
|
try
|
|
|
|
|
{
|
2023-07-16 17:33:15 +02:00
|
|
|
|
File.AppendAllText(logFilePath, logMessage.formattedMessage);
|
2023-05-20 22:56:05 +02:00
|
|
|
|
}
|
2023-07-16 17:33:15 +02:00
|
|
|
|
catch (Exception)
|
2023-05-20 22:56:05 +02:00
|
|
|
|
{
|
2023-07-16 17:33:15 +02:00
|
|
|
|
// ignored
|
2023-05-20 22:56:05 +02:00
|
|
|
|
}
|
2023-05-20 21:47:54 +02:00
|
|
|
|
}
|
|
|
|
|
}
|