2020-07-23 02:24:18 +02:00
using System.IO ;
namespace ExtremelySimpleLogger {
2020-07-23 02:46:34 +02:00
/// <summary>
/// A <see cref="Sink"/> that writes log output to a file.
/// </summary>
2020-07-23 02:24:18 +02:00
public class FileSink : Sink {
2020-07-23 13:51:18 +02:00
private readonly FileInfo file ;
2020-07-23 02:24:18 +02:00
private readonly StreamWriter writer ;
2020-07-23 13:51:18 +02:00
private readonly bool reopenOnWrite ;
2020-07-23 02:24:18 +02:00
2020-07-23 02:46:34 +02:00
/// <summary>
/// Creates a new file sink with the given settings.
/// </summary>
/// <param name="file">The full, or relative, path of the file to write to</param>
/// <param name="append">Whether new output should be appended to the old log file</param>
2020-07-23 13:51:18 +02:00
/// <param name="reopenOnWrite">Whether this file sink should reopen the file every time it logs to it. If this is false, the file will be kept open by this sink.</param>
public FileSink ( string file , bool append , bool reopenOnWrite = false ) :
this ( new FileInfo ( file ) , append , reopenOnWrite ) {
2020-07-23 02:24:18 +02:00
}
2020-07-23 02:46:34 +02:00
/// <summary>
/// Creates a new file sink with the given settings.
/// </summary>
/// <param name="file">The full, or relative, path of the file to write to</param>
/// <param name="append">Whether new output should be appended to the old log file</param>
2020-07-23 13:51:18 +02:00
/// <param name="reopenOnWrite">Whether this file sink should reopen the file every time it logs to it. If this is false, the file will be kept open by this sink.</param>
public FileSink ( FileInfo file , bool append , bool reopenOnWrite = false ) {
this . reopenOnWrite = reopenOnWrite ;
this . file = file ;
2020-07-23 02:24:18 +02:00
var dir = file . Directory ;
if ( dir ! = null & & ! dir . Exists )
dir . Create ( ) ;
if ( ! append & & file . Exists )
file . Delete ( ) ;
2020-07-23 13:51:18 +02:00
if ( ! reopenOnWrite ) {
this . writer = file . AppendText ( ) ;
this . writer . AutoFlush = true ;
}
2020-07-23 02:24:18 +02:00
}
2020-07-23 02:46:34 +02:00
/// <summary>
/// Logs the given message, which has already been formatted using <see cref="Sink.Formatter"/>.
/// </summary>
/// <param name="s">The message to log</param>
2020-07-23 02:24:18 +02:00
public override void Log ( string s ) {
2020-07-23 13:51:18 +02:00
if ( this . reopenOnWrite ) {
using ( var w = this . file . AppendText ( ) )
w . WriteLine ( s ) ;
} else {
this . writer . WriteLine ( s ) ;
}
2020-07-23 02:24:18 +02:00
}
2020-07-23 14:01:44 +02:00
/// Disposes this sink, freeing all of the resources it uses.
public override void Dispose ( ) {
base . Dispose ( ) ;
if ( ! this . reopenOnWrite )
this . writer . Dispose ( ) ;
}
2020-07-23 02:24:18 +02:00
}
}