added DirectorySink

This commit is contained in:
Ellpeck 2020-07-29 15:07:20 +02:00
parent f296c67104
commit 6b500ec693
3 changed files with 92 additions and 1 deletions

View file

@ -0,0 +1,90 @@
using System;
using System.IO;
using System.Linq;
namespace ExtremelySimpleLogger {
/// <summary>
/// A <see cref="Sink"/> that writes log output to a set of directories.
/// This sink differs from <see cref="FileSink"/> in that it manages multiple log files in a directory, where a new file will be created every time the sink is created.
/// Additionally, this sink will automatically delete the oldest log files if the amount of files exceeds a set limit.
/// </summary>
public class DirectorySink : Sink {
private const string DefaultDateFormat = "yy-MM-dd_HH-mm-ss";
private readonly FileInfo file;
private readonly StreamWriter writer;
private readonly bool reopenOnWrite;
/// <summary>
/// Creates a new directory sink with the given settings.
/// </summary>
/// <param name="directory">The directory that this sink should operate in</param>
/// <param name="maxFiles">The maximum amount of files that can exist in the directory before the oldest one gets deleted. 10 by default.</param>
/// <param name="reopenOnWrite">Whether this 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>
/// <param name="dateFormat">The way the name of the current log file gets formatted. <code>yy-MM-dd_HH-mm-ss</code> by default.</param>
public DirectorySink(string directory, int maxFiles = 10, bool reopenOnWrite = false, string dateFormat = DefaultDateFormat) :
this(new DirectoryInfo(directory), maxFiles, reopenOnWrite, dateFormat) {
}
/// <summary>
/// Creates a new directory sink with the given settings.
/// </summary>
/// <param name="directory">The directory that this sink should operate in</param>
/// <param name="maxFiles">The maximum amount of files that can exist in the directory before the oldest one gets deleted. 10 by default.</param>
/// <param name="reopenOnWrite">Whether this 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>
/// <param name="dateFormat">The way the name of the current log file gets formatted. <code>yy-MM-dd_HH-mm-ss</code> by default.</param>
public DirectorySink(DirectoryInfo directory, int maxFiles = 10, bool reopenOnWrite = false, string dateFormat = DefaultDateFormat) {
this.reopenOnWrite = reopenOnWrite;
if (!directory.Exists)
directory.Create();
// delete old files
var files = directory.GetFiles();
if (files.Length >= maxFiles) {
// order files by their creation time so that older files are deleted first
var ordered = files.OrderBy(f => f.CreationTime).ToList();
while (ordered.Count >= maxFiles) {
ordered[0].Delete();
ordered.RemoveAt(0);
}
}
var date = DateTime.Now.ToString(dateFormat);
this.file = new FileInfo(Path.Combine(directory.FullName, $"{date}.txt"));
if (!reopenOnWrite) {
this.writer = this.file.AppendText();
this.writer.AutoFlush = true;
}
}
/// <summary>
/// Logs the given message, which has already been formatted using <see cref="Sink.Formatter"/>.
/// </summary>
/// <param name="logger">The logger that the message was passed to</param>
/// <param name="level">The importance level of this message</param>
/// <param name="s">The message to log</param>
protected override void Log(Logger logger, LogLevel level, string s) {
lock (this.file) {
if (this.reopenOnWrite) {
using (var w = this.file.AppendText())
w.WriteLine(s);
} else {
this.writer.WriteLine(s);
}
}
}
/// <summary>
/// Disposes this sink, freeing all of the resources it uses.
/// </summary>
public override void Dispose() {
base.Dispose();
lock (this.file) {
if (!this.reopenOnWrite)
this.writer.Dispose();
}
}
}
}

View file

@ -10,7 +10,7 @@ namespace ExtremelySimpleLogger {
/// <summary>
/// All of the <see cref="Sink"/> instances that this logger logs to.
/// By default, <see cref="FileSink"/>, <see cref="ConsoleSink"/> and <see cref="StringSink"/> are available.
/// By default, <see cref="FileSink"/>, <see cref="ConsoleSink"/>, <see cref="DirectorySink"/> and <see cref="StringSink"/> are available.
/// </summary>
public List<Sink> Sinks { get; set; } = new List<Sink>();
/// <summary>

View file

@ -22,6 +22,7 @@ var logger = new Logger {
Since there are multiple ways for logging data to be processed, the logger needs to receive a set of `Sink` instances. By default, the following sinks are available:
- `FileSink`, which outputs logging data to a file
- `ConsoleSink`, which outputs logging data to the default console
- `DirectorySink`, which outputs logging data to a set of files and automatically manages how many old logs are kept
- `StringSink`, which stores logging data in a string
There are multiple ways to easily log messages with your newly created logger: