diff --git a/ExtremelySimpleLogger/LogWriter.cs b/ExtremelySimpleLogger/LogWriter.cs new file mode 100644 index 0000000..6f92ea1 --- /dev/null +++ b/ExtremelySimpleLogger/LogWriter.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +namespace ExtremelySimpleLogger { + /// + /// Implementation of a that writes to a . + /// + public class LogWriter : TextWriter { + + /// + /// The log level that this log writer should write with. + /// + public LogLevel Level { + get { + lock (this.logger) + return this.level; + } + set { + lock (this.logger) + this.level = value; + } + } + + /// + public override Encoding Encoding => Encoding.UTF8; + + private readonly StringBuilder line = new StringBuilder(); + private readonly Logger logger; + + private LogLevel level; + + /// + /// Creates a new log writer with the given settings. + /// + /// The logger to write to. + /// The log level to write with. + public LogWriter(Logger logger, LogLevel level = LogLevel.Info) { + this.logger = logger; + this.level = level; + } + + /// + public override void Write(char value) { + lock (this.logger) + this.line.Append(value); + } + + /// + public override void Write(char[] buffer, int index, int count) { + lock (this.logger) + this.line.Append(buffer, index, count); + } + + /// + public override void Write(string value) { + lock (this.logger) + this.line.Append(value); + } + + /// + public override void WriteLine(string value) { + this.Write(value); + this.WriteLine(); + } + + /// + public override void WriteLine() { + this.Flush(); + } + + /// + public override void Flush() { + lock (this.logger) { + this.logger.Log(this.level, this.line); + this.line.Clear(); + } + } + + } +} diff --git a/Sample/Program.cs b/Sample/Program.cs index e521c86..2620791 100644 --- a/Sample/Program.cs +++ b/Sample/Program.cs @@ -39,9 +39,15 @@ 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."); + // we can also use a writer to write to the log + Console.SetError(new LogWriter(logger, LogLevel.Warn)); + Console.Error.WriteLine("This is an error written through serr! Oh no!"); + Console.Error.Write("This is another error, but "); + Console.Error.WriteLine("written in multiple parts!"); + // Once we're done using the logger, we can dispose it so that our FileSink instances free their files logger.Dispose(); } } -} \ No newline at end of file +}