From 5fd708e43f6576cc71b80406de602adbdef98f56 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 4 Nov 2016 19:52:12 -0400 Subject: format & document logging code --- src/StardewModdingAPI.sln.DotSettings | 1 + src/StardewModdingAPI/Log.cs | 159 ++++++++++++++++++++-------------- src/StardewModdingAPI/LogWriter.cs | 96 ++++++++++---------- src/StardewModdingAPI/Logger.cs | 35 +++++--- 4 files changed, 168 insertions(+), 123 deletions(-) diff --git a/src/StardewModdingAPI.sln.DotSettings b/src/StardewModdingAPI.sln.DotSettings index 84c0029d..4c195c13 100644 --- a/src/StardewModdingAPI.sln.DotSettings +++ b/src/StardewModdingAPI.sln.DotSettings @@ -7,6 +7,7 @@ UseExplicitType ID <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> True True True diff --git a/src/StardewModdingAPI/Log.cs b/src/StardewModdingAPI/Log.cs index abf6e36a..ddd82579 100644 --- a/src/StardewModdingAPI/Log.cs +++ b/src/StardewModdingAPI/Log.cs @@ -5,198 +5,227 @@ using System.Threading.Tasks; namespace StardewModdingAPI { + /// A singleton which logs messages to the SMAPI console and log file. public static class Log { + /********* + ** Properties + *********/ /// A pseudorandom number generator used to generate log files. private static readonly Random Random = new Random(); - private static readonly LogWriter _writer; + /// The underlying log writer. + private static readonly LogWriter Writer = LogWriter.Instance; - static Log() - { - _writer = LogWriter.Instance; - } - private static void PrintLog(LogInfo li) - { - _writer.WriteToLog(li); - } - - #region Exception Logging - - /// - /// Catch unhandled exception from the application - /// - /// Should be moved out of here if we do more than just log the exception. + /********* + ** Public methods + *********/ + /**** + ** Exceptions + ****/ + /// Log an exception event. + /// The event sender. + /// The event arguments. public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine("An exception has been caught"); File.WriteAllText(Path.Combine(Constants.LogDir, $"MODDED_ErrorLog.Log_{DateTime.UtcNow.Ticks}.txt"), e.ExceptionObject.ToString()); } - /// - /// Catch thread exception from the application - /// - /// Should be moved out of here if we do more than just log the exception. + /// Log a thread exception event. + /// The event sender. + /// The event arguments. public static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { Console.WriteLine("A thread exception has been caught"); File.WriteAllText(Path.Combine(Constants.LogDir, $"MODDED_ErrorLog.Log_{Log.Random.Next(100000000, 999999999)}.txt"), e.Exception.ToString()); } - #endregion - - #region Sync Logging - /// - /// NOTICE: Sync logging is discouraged. Please use Async instead. - /// - /// Message to log - /// Colour of message - public static void SyncColour(object message, ConsoleColor colour) + /**** + ** Synchronous logging + ****/ + /// Synchronously log a message to the console. NOTE: synchronous logging is discouraged; use asynchronous methods instead. + /// The message to log. + /// The message color. + public static void SyncColour(object message, ConsoleColor color) { - PrintLog(new LogInfo(message?.ToString(), colour)); + Log.PrintLog(new LogInfo(message?.ToString(), color)); } - #endregion - - #region Async Logging - - public static void AsyncColour(object message, ConsoleColor colour) + /**** + ** Asynchronous logging + ****/ + /// Asynchronously log a message to the console with the specified color. + /// The message to log. + /// The message color. + public static void AsyncColour(object message, ConsoleColor color) { - Task.Run(() => { PrintLog(new LogInfo(message?.ToString(), colour)); }); + Task.Run(() => { Log.PrintLog(new LogInfo(message?.ToString(), color)); }); } + /// Asynchronously log a message to the console. + /// The message to log. public static void Async(object message) { - AsyncColour(message?.ToString(), ConsoleColor.Gray); + Log.AsyncColour(message?.ToString(), ConsoleColor.Gray); } + /// Asynchronously log a red message to the console. + /// The message to log. public static void AsyncR(object message) { - AsyncColour(message?.ToString(), ConsoleColor.Red); + Log.AsyncColour(message?.ToString(), ConsoleColor.Red); } + /// Asynchronously log an orange message to the console. + /// The message to log. public static void AsyncO(object message) { - AsyncColour(message.ToString(), ConsoleColor.DarkYellow); + Log.AsyncColour(message.ToString(), ConsoleColor.DarkYellow); } + /// Asynchronously log a yellow message to the console. + /// The message to log. public static void AsyncY(object message) { - AsyncColour(message?.ToString(), ConsoleColor.Yellow); + Log.AsyncColour(message?.ToString(), ConsoleColor.Yellow); } + /// Asynchronously log a green message to the console. + /// The message to log. public static void AsyncG(object message) { - AsyncColour(message?.ToString(), ConsoleColor.Green); + Log.AsyncColour(message?.ToString(), ConsoleColor.Green); } + /// Asynchronously log a cyan message to the console. + /// The message to log. public static void AsyncC(object message) { - AsyncColour(message?.ToString(), ConsoleColor.Cyan); + Log.AsyncColour(message?.ToString(), ConsoleColor.Cyan); } + /// Asynchronously log a magenta message to the console. + /// The message to log. public static void AsyncM(object message) { - AsyncColour(message?.ToString(), ConsoleColor.Magenta); + Log.AsyncColour(message?.ToString(), ConsoleColor.Magenta); } + /// Asynchronously log an error to the console. + /// The message to log. public static void Error(object message) { - AsyncR("[ERROR] " + message); + Log.AsyncR("[ERROR] " + message); } + /// Asynchronously log a success message to the console. + /// The message to log. public static void Success(object message) { - AsyncG("[SUCCESS] " + message); + Log.AsyncG("[SUCCESS] " + message); } + /// Asynchronously log an info message to the console. + /// The message to log. public static void Info(object message) { - AsyncY("[INFO] " + message); + Log.AsyncY("[INFO] " + message); } + // unused? public static void Out(object message) { - Async("[OUT] " + message); + Log.Async("[OUT] " + message); } + /// Asynchronously log a debug message to the console. + /// The message to log. public static void Debug(object message) { - AsyncO("[DEBUG] " + message); + Log.AsyncO("[DEBUG] " + message); } - #endregion - - #region ToRemove - + /**** + ** Obsolete + ****/ public static void LogValueNotSpecified() { - AsyncR(" must be specified"); + Log.AsyncR(" must be specified"); } public static void LogObjectValueNotSpecified() { - AsyncR(" and must be specified"); + Log.AsyncR(" and must be specified"); } public static void LogValueInvalid() { - AsyncR(" is invalid"); + Log.AsyncR(" is invalid"); } public static void LogObjectInvalid() { - AsyncR(" is invalid"); + Log.AsyncR(" is invalid"); } public static void LogValueNotInt32() { - AsyncR(" must be a whole number (Int32)"); + Log.AsyncR(" must be a whole number (Int32)"); } [Obsolete("Parameter 'values' is no longer supported. Format before logging.")] private static void PrintLog(object message, bool disableLogging, params object[] values) { - PrintLog(new LogInfo(message?.ToString())); + Log.PrintLog(new LogInfo(message?.ToString())); } [Obsolete("Parameter 'values' is no longer supported. Format before logging.")] public static void Success(object message, params object[] values) { - Success(message); + Log.Success(message); } [Obsolete("Parameter 'values' is no longer supported. Format before logging.")] public static void Verbose(object message, params object[] values) { - Out(message); + Log.Out(message); } [Obsolete("Parameter 'values' is no longer supported. Format before logging.")] public static void Comment(object message, params object[] values) { - AsyncC(message); + Log.AsyncC(message); } [Obsolete("Parameter 'values' is no longer supported. Format before logging.")] public static void Info(object message, params object[] values) { - Info(message); + Log.Info(message); } [Obsolete("Parameter 'values' is no longer supported. Format before logging.")] public static void Error(object message, params object[] values) { - Error(message); + Log.Error(message); } [Obsolete("Parameter 'values' is no longer supported. Format before logging.")] public static void Debug(object message, params object[] values) { - Debug(message); + Log.Debug(message); } - #endregion + + /********* + ** Private methods + *********/ + /// Write a message to the log. + /// The message to write. + private static void PrintLog(LogInfo message) + { + Log.Writer.WriteToLog(message); + } } } \ No newline at end of file diff --git a/src/StardewModdingAPI/LogWriter.cs b/src/StardewModdingAPI/LogWriter.cs index 18c940c8..139d89bf 100644 --- a/src/StardewModdingAPI/LogWriter.cs +++ b/src/StardewModdingAPI/LogWriter.cs @@ -5,35 +5,36 @@ using System.Linq; namespace StardewModdingAPI { - /// - /// A Logging class implementing the Singleton pattern and an internal Queue to be flushed perdiodically - /// + /// A log writer which queues messages for output, and periodically flushes them to the console and log file. public class LogWriter { + /********* + ** Properties + *********/ + /// The singleton instance. private static LogWriter _instance; - private static ConcurrentQueue _logQueue; - private static StreamWriter _stream; - /// - /// Private to prevent creation of other instances - /// - private LogWriter() - { - } + /// The queued messages to flush. + private static ConcurrentQueue Queue; + + /// The underlying file stream. + private static StreamWriter FileStream; - /// - /// Exposes _instace and creates a new one if it is null - /// + + /********* + ** Accessors + *********/ + /// The singleton instance. internal static LogWriter Instance { get { - if (_instance == null) + if (LogWriter._instance == null) { - _instance = new LogWriter(); + LogWriter._instance = new LogWriter(); // Field cannot be used by anything else regardless, do not surround with lock { } // ReSharper disable once InconsistentlySynchronizedField - _logQueue = new ConcurrentQueue(); + LogWriter.Queue = new ConcurrentQueue(); Console.WriteLine(Constants.LogPath); // If the ErrorLogs dir doesn't exist StreamWriter will throw an exception. @@ -42,57 +43,56 @@ namespace StardewModdingAPI Directory.CreateDirectory(Constants.LogDir); } - _stream = new StreamWriter(Constants.LogPath, false); + LogWriter.FileStream = new StreamWriter(Constants.LogPath, false); Console.WriteLine("Created log instance"); } - return _instance; + return LogWriter._instance; } } - /// - /// Writes into the ConcurrentQueue the Message specified - /// - /// The message to write to the log + + /********* + ** Public methods + *********/ + /// Queue a message for output. + /// The message to log. public void WriteToLog(string message) { - lock (_logQueue) + lock (LogWriter.Queue) { var logEntry = new LogInfo(message); - _logQueue.Enqueue(logEntry); + LogWriter.Queue.Enqueue(logEntry); - if (_logQueue.Any()) - { - FlushLog(); - } + if (LogWriter.Queue.Any()) + this.FlushLog(); } } - /// - /// Writes into the ConcurrentQueue the Entry specified - /// - /// The logEntry to write to the log - public void WriteToLog(LogInfo logEntry) + /// Queue a message for output. + /// The message to log. + public void WriteToLog(LogInfo message) { - lock (_logQueue) + lock (LogWriter.Queue) { - _logQueue.Enqueue(logEntry); - - if (_logQueue.Any()) - { - FlushLog(); - } + LogWriter.Queue.Enqueue(message); + if (LogWriter.Queue.Any()) + this.FlushLog(); } } - /// - /// Flushes the ConcurrentQueue to the log file specified in Constants - /// + /********* + ** Private methods + *********/ + /// Construct an instance. + private LogWriter() { } + + /// Flush the underlying queue to the console and file. private void FlushLog() { - lock (_stream) + lock (LogWriter.FileStream) { LogInfo entry; - while (_logQueue.TryDequeue(out entry)) + while (LogWriter.Queue.TryDequeue(out entry)) { string m = $"[{entry.LogTime}] {entry.Message}"; @@ -100,9 +100,9 @@ namespace StardewModdingAPI Console.WriteLine(m); Console.ForegroundColor = ConsoleColor.Gray; - _stream.WriteLine(m); + LogWriter.FileStream.WriteLine(m); } - _stream.Flush(); + LogWriter.FileStream.Flush(); } } } diff --git a/src/StardewModdingAPI/Logger.cs b/src/StardewModdingAPI/Logger.cs index 0f40cd25..f0f08e4f 100644 --- a/src/StardewModdingAPI/Logger.cs +++ b/src/StardewModdingAPI/Logger.cs @@ -2,24 +2,39 @@ namespace StardewModdingAPI { - /// - /// A struct to store the message and the Date and Time the log entry was created - /// + /// A message queued for log output. public struct LogInfo { + /********* + ** Accessors + *********/ + /// The message to log. public string Message { get; set; } - public string LogTime { get; set; } + + /// The log date. public string LogDate { get; set; } + + /// The log time. + public string LogTime { get; set; } + + /// The message color. public ConsoleColor Colour { get; set; } - public LogInfo(string message, ConsoleColor colour = ConsoleColor.Gray) + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The message to log. + /// The message color. + public LogInfo(string message, ConsoleColor color = ConsoleColor.Gray) { if (string.IsNullOrEmpty(message)) message = "[null]"; - Message = message; - LogDate = DateTime.Now.ToString("yyyy-MM-dd"); - LogTime = DateTime.Now.ToString("hh:mm:ss.fff tt"); - Colour = colour; + this.Message = message; + this.LogDate = DateTime.Now.ToString("yyyy-MM-dd"); + this.LogTime = DateTime.Now.ToString("hh:mm:ss.fff tt"); + this.Colour = color; } } -} \ No newline at end of file +} -- cgit