using System; using System.Linq; using System.Threading; using StardewModdingAPI.Framework.Logging; using StardewModdingAPI.Internal.ConsoleWriting; namespace StardewModdingAPI.Framework { /// Encapsulates monitoring and logic for a given module. internal class Monitor : IMonitor { /********* ** Properties *********/ /// The name of the module which logs messages using this instance. private readonly string Source; /// Handles writing color-coded text to the console. private readonly ColorfulConsoleWriter ConsoleWriter; /// Manages access to the console output. private readonly ConsoleInterceptionManager ConsoleInterceptor; /// The log file to which to write messages. private readonly LogFileManager LogFile; /// The maximum length of the values. private static readonly int MaxLevelLength = (from level in Enum.GetValues(typeof(LogLevel)).Cast() select level.ToString().Length).Max(); /// Propagates notification that SMAPI should exit. private readonly CancellationTokenSource ExitTokenSource; /********* ** Accessors *********/ /// Whether SMAPI is aborting. Mods don't need to worry about this unless they have background tasks. public bool IsExiting => this.ExitTokenSource.IsCancellationRequested; /// Whether verbose logging is enabled. This enables more detailed diagnostic messages than are normally needed. public bool IsVerbose { get; } /// Whether to show the full log stamps (with time/level/logger) in the console. If false, shows a simplified stamp with only the logger. internal bool ShowFullStampInConsole { get; set; } /// Whether to show trace messages in the console. internal bool ShowTraceInConsole { get; set; } /// Whether to write anything to the console. This should be disabled if no console is available. internal bool WriteToConsole { get; set; } = true; /********* ** Public methods *********/ /// Construct an instance. /// The name of the module which logs messages using this instance. /// Intercepts access to the console output. /// The log file to which to write messages. /// Propagates notification that SMAPI should exit. /// The console color scheme to use. /// Whether verbose logging is enabled. This enables more detailed diagnostic messages than are normally needed. public Monitor(string source, ConsoleInterceptionManager consoleInterceptor, LogFileManager logFile, CancellationTokenSource exitTokenSource, MonitorColorScheme colorScheme, bool isVerbose) { // validate if (string.IsNullOrWhiteSpace(source)) throw new ArgumentException("The log source cannot be empty."); // initialise this.Source = source; this.LogFile = logFile ?? throw new ArgumentNullException(nameof(logFile), "The log file manager cannot be null."); this.ConsoleWriter = new ColorfulConsoleWriter(Constants.Platform, colorScheme); this.ConsoleInterceptor = consoleInterceptor; this.ExitTokenSource = exitTokenSource; this.IsVerbose = isVerbose; } /// Log a message for the player or developer. /// The message to log. /// The log severity level. public void Log(string message, LogLevel level = LogLevel.Debug) { this.LogImpl(this.Source, message, (ConsoleLogLevel)level); } /// Log a message that only appears when is enabled. /// The message to log. public void VerboseLog(string message) { if (this.IsVerbose) this.Log(message, LogLevel.Trace); } /// 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. /// The reason for the shutdown. public void ExitGameImmediately(string reason) { this.LogFatal($"{this.Source} requested an immediate game shutdown: {reason}"); this.ExitTokenSource.Cancel(); } /// Write a newline to the console and log file. internal void Newline() { if (this.WriteToConsole) this.ConsoleInterceptor.ExclusiveWriteWithoutInterception(Console.WriteLine); this.LogFile.WriteLine(""); } /// Log console input from the user. /// The user input to log. internal void LogUserInput(string input) { // user input already appears in the console, so just need to write to file string prefix = this.GenerateMessagePrefix(this.Source, (ConsoleLogLevel)LogLevel.Info); this.LogFile.WriteLine($"{prefix} $>{input}"); } /********* ** Private methods *********/ /// Log a fatal error message. /// The message to log. private void LogFatal(string message) { this.LogImpl(this.Source, message, ConsoleLogLevel.Critical); } /// Write a message line to the log. /// The name of the mod logging the message. /// The message to log. /// The log level. private void LogImpl(string source, string message, ConsoleLogLevel level) { // generate message string prefix = this.GenerateMessagePrefix(source, level); string fullMessage = $"{prefix} {message}"; string consoleMessage = this.ShowFullStampInConsole ? fullMessage : $"[{source}] {message}"; // write to console if (this.WriteToConsole && (this.ShowTraceInConsole || level != ConsoleLogLevel.Trace)) { this.ConsoleInterceptor.ExclusiveWriteWithoutInterception(() => { this.ConsoleWriter.WriteLine(consoleMessage, level); }); } // write to log file this.LogFile.WriteLine(fullMessage); } /// Generate a message prefix for the current time. /// The name of the mod logging the message. /// The log level. private string GenerateMessagePrefix(string source, ConsoleLogLevel level) { string levelStr = level.ToString().ToUpper().PadRight(Monitor.MaxLevelLength); return $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}]"; } } }