From 46b7d7a4001e209d7201ed5cad38cad2f1ad2a7f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 11 Feb 2017 01:15:56 -0500 Subject: redirect the game's debug messages into trace logs (#233) The game writes debug messages directly to the console, which shows up for SMAPI users. This commit redirects direct console messages to a monitor. --- .../Framework/Logging/InterceptingTextWriter.cs | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/StardewModdingAPI/Framework/Logging/InterceptingTextWriter.cs (limited to 'src/StardewModdingAPI/Framework/Logging/InterceptingTextWriter.cs') diff --git a/src/StardewModdingAPI/Framework/Logging/InterceptingTextWriter.cs b/src/StardewModdingAPI/Framework/Logging/InterceptingTextWriter.cs new file mode 100644 index 00000000..14789109 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Logging/InterceptingTextWriter.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace StardewModdingAPI.Framework.Logging +{ + /// A text writer which allows intercepting output. + internal class InterceptingTextWriter : TextWriter + { + /********* + ** Properties + *********/ + /// The current line being intercepted. + private readonly List Line = new List(); + + + /********* + ** Accessors + *********/ + /// The underlying console output. + public TextWriter Out { get; } + + /// The character encoding in which the output is written. + public override Encoding Encoding => this.Out.Encoding; + + /// Whether to intercept console output. + public bool ShouldIntercept { get; set; } + + /// The event raised when a line of text is intercepted. + public event Action OnLineIntercepted; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The underlying output writer. + public InterceptingTextWriter(TextWriter output) + { + this.Out = output; + } + + /// Writes a character to the text string or stream. + /// The character to write to the text stream. + public override void Write(char ch) + { + // intercept + if (this.ShouldIntercept) + { + switch (ch) + { + case '\r': + return; + + case '\n': + this.OnLineIntercepted?.Invoke(new string(this.Line.ToArray())); + this.Line.Clear(); + break; + + default: + this.Line.Add(ch); + break; + } + } + + // pass through + else + this.Out.Write(ch); + } + + /// Releases the unmanaged resources used by the and optionally releases the managed resources. + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected override void Dispose(bool disposing) + { + this.OnLineIntercepted = null; + } + } +} -- cgit