allow loggers and sinks to be disposable

This commit is contained in:
Ellpeck 2020-07-23 14:01:44 +02:00
parent b3878887e3
commit 80123b7748
4 changed files with 26 additions and 2 deletions

View file

@ -56,5 +56,12 @@ namespace ExtremelySimpleLogger {
}
}
/// Disposes this sink, freeing all of the resources it uses.
public override void Dispose() {
base.Dispose();
if(!this.reopenOnWrite)
this.writer.Dispose();
}
}
}

View file

@ -8,7 +8,7 @@ namespace ExtremelySimpleLogger {
/// To start logging with a logger, its <see cref="Sinks"/> need to be initialized.
/// There are two default implementations: <see cref="FileSink"/>, <see cref="ConsoleSink"/> and <see cref="StringSink"/>.
/// </summary>
public class Logger {
public class Logger : IDisposable {
/// <summary>
/// All of the <see cref="Sink"/> instances that this logger logs to.
@ -91,5 +91,13 @@ namespace ExtremelySimpleLogger {
/// <param name="e">An optional exception whose stack trace will be appended to the message</param>
public void Fatal(object message, Exception e = null) => this.Log(LogLevel.Fatal, message, e);
/// <summary>
/// Disposes this logger, freeing all of the resources associated with its <see cref="Sinks"/>.
/// </summary>
public void Dispose() {
foreach (var sink in this.Sinks)
sink.Dispose();
}
}
}

View file

@ -6,7 +6,7 @@ namespace ExtremelySimpleLogger {
/// A sink is a way for log messages passed to a <see cref="Logger"/> to be processed in a certain way.
/// By default, <see cref="FileSink"/> and <see cref="ConsoleSink"/> are available.
/// </summary>
public abstract class Sink {
public abstract class Sink : IDisposable {
/// <summary>
/// The minimum level that a log message needs to have for it to be processed by this sink.
@ -81,5 +81,11 @@ namespace ExtremelySimpleLogger {
/// <param name="e">An optional exception whose stack trace will be appended to the message</param>
public delegate string LogFormatter(Logger logger, LogLevel level, object message, Exception e = null);
/// <summary>
/// Disposes this sink, freeing all of the resources it uses.
/// </summary>
public virtual void Dispose() {
}
}
}

View file

@ -36,6 +36,9 @@ namespace Sample {
logger.Log(LogLevel.Trace, "This is a message that only the file sink will receive, since its minimum level is lower.");
logger.Log(LogLevel.Info, "The program finished.");
// Once we're done using the logger, we can dispose it so that our FileSink instances free their files
logger.Dispose();
}
}