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. --- release-notes.md | 6 +- src/StardewModdingAPI/Framework/LogFileManager.cs | 48 ------------ .../Logging/ConsoleInterceptionManager.cs | 86 ++++++++++++++++++++++ .../Framework/Logging/InterceptingTextWriter.cs | 79 ++++++++++++++++++++ .../Framework/Logging/LogFileManager.cs | 48 ++++++++++++ src/StardewModdingAPI/Framework/Monitor.cs | 56 ++++++-------- src/StardewModdingAPI/Framework/SGame.cs | 1 - src/StardewModdingAPI/Program.cs | 20 +++-- src/StardewModdingAPI/StardewModdingAPI.csproj | 4 +- 9 files changed, 257 insertions(+), 91 deletions(-) delete mode 100644 src/StardewModdingAPI/Framework/LogFileManager.cs create mode 100644 src/StardewModdingAPI/Framework/Logging/ConsoleInterceptionManager.cs create mode 100644 src/StardewModdingAPI/Framework/Logging/InterceptingTextWriter.cs create mode 100644 src/StardewModdingAPI/Framework/Logging/LogFileManager.cs diff --git a/release-notes.md b/release-notes.md index e6becdbd..e3e8752b 100644 --- a/release-notes.md +++ b/release-notes.md @@ -4,13 +4,13 @@ See [log](https://github.com/Pathoschild/SMAPI/compare/1.8...1.9). For players: -* Updated for Stardew Valley 1.2. +* Updated for Stardew Valley 1.2. Most mods are now rewritten for compatibility; some mods require an update from their authors. * Simplified log filename. -* SMAPI now rewrites most mods for Stardew Valley 1.2 compatibility. +* Fixed game's debug output being shown in the console for all users. For mod developers: * Added `SaveEvents.AfterReturnToTitle` event. -* Added `GetPrivateProperty` to reflection helper. +* Added `GetPrivateProperty` reflection helper. * Many deprecated APIs have been removed; see the [deprecation guide](http://canimod.com/guides/updating-a-smapi-mod) for more information. * Log files now always use `\r\n` to simplify crossplatform viewing. diff --git a/src/StardewModdingAPI/Framework/LogFileManager.cs b/src/StardewModdingAPI/Framework/LogFileManager.cs deleted file mode 100644 index 80437e9c..00000000 --- a/src/StardewModdingAPI/Framework/LogFileManager.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.IO; - -namespace StardewModdingAPI.Framework -{ - /// Manages reading and writing to log file. - internal class LogFileManager : IDisposable - { - /********* - ** Properties - *********/ - /// The underlying stream writer. - private readonly StreamWriter Stream; - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The log file to write. - public LogFileManager(string path) - { - // create log directory if needed - string logDir = Path.GetDirectoryName(path); - if (logDir == null) - throw new ArgumentException($"The log path '{path}' is not valid."); - Directory.CreateDirectory(logDir); - - // open log file stream - this.Stream = new StreamWriter(path, append: false) { AutoFlush = true }; - } - - /// Write a message to the log. - /// The message to log. - public void WriteLine(string message) - { - // always use Windows-style line endings for convenience - // (Linux/Mac editors are fine with them, Windows editors often require them) - this.Stream.Write(message + "\r\n"); - } - - /// Release all resources. - public void Dispose() - { - this.Stream.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/StardewModdingAPI/Framework/Logging/ConsoleInterceptionManager.cs b/src/StardewModdingAPI/Framework/Logging/ConsoleInterceptionManager.cs new file mode 100644 index 00000000..d84671ee --- /dev/null +++ b/src/StardewModdingAPI/Framework/Logging/ConsoleInterceptionManager.cs @@ -0,0 +1,86 @@ +using System; + +namespace StardewModdingAPI.Framework.Logging +{ + /// Manages console output interception. + internal class ConsoleInterceptionManager : IDisposable + { + /********* + ** Properties + *********/ + /// The intercepting console writer. + private readonly InterceptingTextWriter Output; + + + /********* + ** Accessors + *********/ + /// Whether the current console supports color formatting. + public bool SupportsColor { get; } + + /// The event raised when something writes a line to the console directly. + public event Action OnLineIntercepted; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public ConsoleInterceptionManager() + { + // redirect output through interceptor + this.Output = new InterceptingTextWriter(Console.Out); + this.Output.OnLineIntercepted += line => this.OnLineIntercepted?.Invoke(line); + Console.SetOut(this.Output); + + // test color support + this.SupportsColor = this.TestColorSupport(); + } + + /// Get an exclusive lock and write to the console output without interception. + /// The action to perform within the exclusive write block. + public void ExclusiveWriteWithoutInterception(Action action) + { + lock (Console.Out) + { + try + { + this.Output.ShouldIntercept = false; + action(); + } + finally + { + this.Output.ShouldIntercept = true; + } + } + } + + /// Release all resources. + public void Dispose() + { + Console.SetOut(this.Output.Out); + this.Output.Dispose(); + } + + + /********* + ** private methods + *********/ + /// Test whether the current console supports color formatting. + private bool TestColorSupport() + { + try + { + this.ExclusiveWriteWithoutInterception(() => + { + Console.ForegroundColor = Console.ForegroundColor; + }); + return true; + } + catch (Exception) + { + return false; // Mono bug + } + } + } +} 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; + } + } +} diff --git a/src/StardewModdingAPI/Framework/Logging/LogFileManager.cs b/src/StardewModdingAPI/Framework/Logging/LogFileManager.cs new file mode 100644 index 00000000..1f6ade1d --- /dev/null +++ b/src/StardewModdingAPI/Framework/Logging/LogFileManager.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; + +namespace StardewModdingAPI.Framework.Logging +{ + /// Manages reading and writing to log file. + internal class LogFileManager : IDisposable + { + /********* + ** Properties + *********/ + /// The underlying stream writer. + private readonly StreamWriter Stream; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The log file to write. + public LogFileManager(string path) + { + // create log directory if needed + string logDir = Path.GetDirectoryName(path); + if (logDir == null) + throw new ArgumentException($"The log path '{path}' is not valid."); + Directory.CreateDirectory(logDir); + + // open log file stream + this.Stream = new StreamWriter(path, append: false) { AutoFlush = true }; + } + + /// Write a message to the log. + /// The message to log. + public void WriteLine(string message) + { + // always use Windows-style line endings for convenience + // (Linux/Mac editors are fine with them, Windows editors often require them) + this.Stream.Write(message + "\r\n"); + } + + /// Release all resources. + public void Dispose() + { + this.Stream.Dispose(); + } + } +} diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs index 39b567d8..33c1bbf4 100644 --- a/src/StardewModdingAPI/Framework/Monitor.cs +++ b/src/StardewModdingAPI/Framework/Monitor.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using StardewModdingAPI.Framework.Logging; namespace StardewModdingAPI.Framework { @@ -13,6 +14,9 @@ namespace StardewModdingAPI.Framework /// The name of the module which logs messages using this instance. private readonly string Source; + /// Manages access to the console output. + private readonly ConsoleInterceptionManager ConsoleManager; + /// The log file to which to write messages. private readonly LogFileManager LogFile; @@ -34,9 +38,6 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ - /// Whether the current console supports color codes. - internal static readonly bool ConsoleSupportsColor = Monitor.GetConsoleSupportsColor(); - /// Whether to show trace messages in the console. internal bool ShowTraceInConsole { get; set; } @@ -49,8 +50,9 @@ namespace StardewModdingAPI.Framework *********/ /// Construct an instance. /// The name of the module which logs messages using this instance. + /// Manages access to the console output. /// The log file to which to write messages. - public Monitor(string source, LogFileManager logFile) + public Monitor(string source, ConsoleInterceptionManager consoleManager, LogFileManager logFile) { // validate if (string.IsNullOrWhiteSpace(source)) @@ -61,6 +63,7 @@ namespace StardewModdingAPI.Framework // initialise this.Source = source; this.LogFile = logFile; + this.ConsoleManager = consoleManager; } /// Log a message for the player or developer. @@ -68,7 +71,7 @@ namespace StardewModdingAPI.Framework /// The log severity level. public void Log(string message, LogLevel level = LogLevel.Debug) { - this.LogImpl(this.Source, message, Monitor.Colors[level], level); + this.LogImpl(this.Source, message, level, Monitor.Colors[level]); } /// Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs. @@ -83,8 +86,7 @@ namespace StardewModdingAPI.Framework /// The message to log. internal void LogFatal(string message) { - Console.BackgroundColor = ConsoleColor.Red; - this.LogImpl(this.Source, message, ConsoleColor.White, LogLevel.Error); + this.LogImpl(this.Source, message, LogLevel.Error, ConsoleColor.White, background: ConsoleColor.Red); } /// Log a message for the player or developer, using the specified console color. @@ -95,7 +97,7 @@ namespace StardewModdingAPI.Framework [Obsolete("This method is provided for backwards compatibility and otherwise should not be used. Use " + nameof(Monitor) + "." + nameof(Monitor.Log) + " instead.")] internal void LegacyLog(string source, string message, ConsoleColor color, LogLevel level = LogLevel.Debug) { - this.LogImpl(source, message, color, level); + this.LogImpl(source, message, level, color); } @@ -105,9 +107,10 @@ namespace StardewModdingAPI.Framework /// Write a message line to the log. /// The name of the mod logging the message. /// The message to log. - /// The console color. /// The log level. - private void LogImpl(string source, string message, ConsoleColor color, LogLevel level) + /// The console foreground color. + /// The console background color (or null to leave it as-is). + private void LogImpl(string source, string message, LogLevel level, ConsoleColor color, ConsoleColor? background = null) { // generate message string levelStr = level.ToString().ToUpper().PadRight(Monitor.MaxLevelLength); @@ -116,30 +119,19 @@ namespace StardewModdingAPI.Framework // log if (this.WriteToConsole && (this.ShowTraceInConsole || level != LogLevel.Trace)) { - if (Monitor.ConsoleSupportsColor) + this.ConsoleManager.ExclusiveWriteWithoutInterception(() => { - Console.ForegroundColor = color; - Console.WriteLine(message); - Console.ResetColor(); - } - else - Console.WriteLine(message); + if (this.ConsoleManager.SupportsColor) + { + Console.ForegroundColor = color; + Console.WriteLine(message); + Console.ResetColor(); + } + else + Console.WriteLine(message); + }); } this.LogFile.WriteLine(message); } - - /// Test whether the current console supports color formatting. - private static bool GetConsoleSupportsColor() - { - try - { - Console.ForegroundColor = Console.ForegroundColor; - return true; - } - catch (Exception) - { - return false; // Mono bug - } - } } -} \ No newline at end of file +} diff --git a/src/StardewModdingAPI/Framework/SGame.cs b/src/StardewModdingAPI/Framework/SGame.cs index 6a751b85..9e269df3 100644 --- a/src/StardewModdingAPI/Framework/SGame.cs +++ b/src/StardewModdingAPI/Framework/SGame.cs @@ -1170,7 +1170,6 @@ namespace StardewModdingAPI.Framework // after exit to title if (this.IsWorldReady && this.IsExiting && Game1.activeClickableMenu is TitleMenu) { - Console.WriteLine($"{Game1.currentGameTime.TotalGameTime}: after return to title"); SaveEvents.InvokeAfterReturnToTitle(this.Monitor); this.AfterLoadTimer = 5; this.IsExiting = false; diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index 75be23f2..a6302540 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -13,6 +13,7 @@ using Newtonsoft.Json; using StardewModdingAPI.AssemblyRewriters; using StardewModdingAPI.Events; using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Logging; using StardewModdingAPI.Framework.Models; using StardewValley; using Monitor = StardewModdingAPI.Framework.Monitor; @@ -42,8 +43,11 @@ namespace StardewModdingAPI /// The log file to which to write messages. private static readonly LogFileManager LogFile = new LogFileManager(Constants.LogPath); + /// Manages console output interception. + private static readonly ConsoleInterceptionManager ConsoleManager = new ConsoleInterceptionManager(); + /// The core logger for SMAPI. - private static readonly Monitor Monitor = new Monitor("SMAPI", Program.LogFile); + private static readonly Monitor Monitor = new Monitor("SMAPI", Program.ConsoleManager, Program.LogFile); /// The user settings for SMAPI. private static UserSettings Settings; @@ -87,14 +91,12 @@ namespace StardewModdingAPI /// The command-line arguments. private static void Main(string[] args) { - // set log options + // initialise logging Program.Monitor.WriteToConsole = !args.Contains("--no-terminal"); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); // for consistent log formatting - - // add info header Program.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Game1.version} on {Environment.OSVersion}", LogLevel.Info); - // initialise user settings + // read config { string settingsPath = Constants.ApiConfigPath; if (File.Exists(settingsPath)) @@ -108,6 +110,12 @@ namespace StardewModdingAPI File.WriteAllText(settingsPath, JsonConvert.SerializeObject(Program.Settings, Formatting.Indented)); } + // redirect direct console output + { + IMonitor monitor = Program.GetSecondaryMonitor("Console.Out"); + Program.ConsoleManager.OnLineIntercepted += line => monitor.Log(line, LogLevel.Trace); + } + // add warning headers if (Program.Settings.DeveloperMode) { @@ -574,7 +582,7 @@ namespace StardewModdingAPI /// The name of the module which will log messages with this instance. private static Monitor GetSecondaryMonitor(string name) { - return new Monitor(name, Program.LogFile) { WriteToConsole = Program.Monitor.WriteToConsole, ShowTraceInConsole = Program.Settings.DeveloperMode }; + return new Monitor(name, Program.ConsoleManager, Program.LogFile) { WriteToConsole = Program.Monitor.WriteToConsole, ShowTraceInConsole = Program.Settings.DeveloperMode }; } } } diff --git a/src/StardewModdingAPI/StardewModdingAPI.csproj b/src/StardewModdingAPI/StardewModdingAPI.csproj index 896721ea..ae08012d 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.csproj +++ b/src/StardewModdingAPI/StardewModdingAPI.csproj @@ -145,6 +145,8 @@ + + @@ -166,7 +168,7 @@ - + -- cgit