2023-05-20 21:47:54 +02:00
using System.Text ;
using System.Text.Json.Serialization ;
namespace Logging ;
public class FileLogger : LoggerBase
{
private string logFilePath { get ; }
2023-05-21 15:33:01 +02:00
private const int MaxNumberOfLogFiles = 5 ;
2023-05-20 21:47:54 +02:00
public FileLogger ( string logFilePath , TextWriter ? stdOut , Encoding ? encoding = null ) : base ( stdOut , encoding )
{
this . logFilePath = logFilePath ;
2023-05-21 15:33:01 +02:00
//Remove oldest logfile if more than MaxNumberOfLogFiles
string parentFolderPath = Path . GetDirectoryName ( logFilePath ) ! ;
for ( int fileCount = new DirectoryInfo ( parentFolderPath ) . EnumerateFiles ( ) . Count ( ) ; fileCount > MaxNumberOfLogFiles - 1 ; fileCount - - ) //-1 because we create own logfile later
File . Delete ( new DirectoryInfo ( parentFolderPath ) . 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
{
File . AppendAllText ( logFilePath , logMessage . ToString ( ) ) ;
}
catch ( Exception e )
{
stdOut ? . WriteLine ( e ) ;
}
2023-05-20 21:47:54 +02:00
}
}