You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

415 lines
16 KiB

4 years ago
4 years ago
  1. using IPA.Config;
  2. using IPA.Logging.Printers;
  3. using IPA.Utilities;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading;
  11. namespace IPA.Logging
  12. {
  13. /// <summary>
  14. /// The default (and standard) <see cref="Logger"/> implementation.
  15. /// </summary>
  16. /// <remarks>
  17. /// <see cref="StandardLogger"/> uses a multi-threaded approach to logging. All actual I/O is done on another thread,
  18. /// where all messaged are guaranteed to be logged in the order they appeared. It is up to the printers to format them.
  19. ///
  20. /// This logger supports child loggers. Use <see cref="LoggerExtensions.GetChildLogger"/> to safely get a child.
  21. /// The modification of printers on a parent are reflected down the chain.
  22. /// </remarks>
  23. public class StandardLogger : Logger
  24. {
  25. private static readonly List<LogPrinter> defaultPrinters = new List<LogPrinter>()
  26. {
  27. new GlobalLogFilePrinter()
  28. };
  29. static StandardLogger()
  30. {
  31. ConsoleColorSupport();
  32. }
  33. private static bool addedConsolePrinters;
  34. private static bool finalizedDefaultPrinters;
  35. internal static void ConsoleColorSupport()
  36. {
  37. if (!addedConsolePrinters && !finalizedDefaultPrinters && WinConsole.IsInitialized )
  38. {
  39. defaultPrinters.AddRange(new []
  40. {
  41. new ColoredConsolePrinter()
  42. {
  43. Filter = LogLevel.TraceOnly,
  44. Color = ConsoleColor.DarkMagenta,
  45. },
  46. new ColoredConsolePrinter()
  47. {
  48. Filter = LogLevel.DebugOnly,
  49. Color = ConsoleColor.Green,
  50. },
  51. new ColoredConsolePrinter()
  52. {
  53. Filter = LogLevel.InfoOnly,
  54. Color = ConsoleColor.White,
  55. },
  56. new ColoredConsolePrinter()
  57. {
  58. Filter = LogLevel.NoticeOnly,
  59. Color = ConsoleColor.Cyan
  60. },
  61. new ColoredConsolePrinter()
  62. {
  63. Filter = LogLevel.WarningOnly,
  64. Color = ConsoleColor.Yellow,
  65. },
  66. new ColoredConsolePrinter()
  67. {
  68. Filter = LogLevel.ErrorOnly,
  69. Color = ConsoleColor.Red,
  70. },
  71. new ColoredConsolePrinter()
  72. {
  73. Filter = LogLevel.CriticalOnly,
  74. Color = ConsoleColor.Magenta,
  75. }
  76. });
  77. addedConsolePrinters = true;
  78. }
  79. }
  80. /// <summary>
  81. /// The <see cref="TextWriter"/> for writing directly to the console window, or stdout if no window open.
  82. /// </summary>
  83. /// <value>a <see cref="TextWriter"/> for the current primary text output</value>
  84. public static TextWriter ConsoleWriter { get; internal set; } = Console.Out;
  85. /// <summary>
  86. /// Adds to the default printer pool that all printers inherit from. Printers added this way will be passed every message from every logger.
  87. /// </summary>
  88. /// <param name="printer">the printer to add</param>
  89. internal static void AddDefaultPrinter(LogPrinter printer)
  90. {
  91. defaultPrinters.Add(printer);
  92. }
  93. private readonly string logName;
  94. private static bool showSourceClass;
  95. /// <summary>
  96. /// All levels defined by this filter will be sent to loggers. All others will be ignored.
  97. /// </summary>
  98. /// <value>the global filter level</value>
  99. public static LogLevel PrintFilter { get; internal set; } = LogLevel.All;
  100. private static bool showTrace = false;
  101. private readonly List<LogPrinter> printers = new List<LogPrinter>();
  102. private readonly StandardLogger parent;
  103. private readonly Dictionary<string, StandardLogger> children = new Dictionary<string, StandardLogger>();
  104. /// <summary>
  105. /// Configures internal debug settings based on the config passed in.
  106. /// </summary>
  107. internal static void Configure()
  108. {
  109. showSourceClass = SelfConfig.Debug_.ShowCallSource_;
  110. PrintFilter = SelfConfig.Debug_.ShowDebug_ ? LogLevel.All : LogLevel.InfoUp;
  111. showTrace = SelfConfig.Debug_.ShowTrace_;
  112. }
  113. private StandardLogger(StandardLogger parent, string subName)
  114. {
  115. logName = $"{parent.logName}/{subName}";
  116. this.parent = parent;
  117. printers = new List<LogPrinter>();
  118. if (!SelfConfig.Debug_.CondenseModLogs_)
  119. printers.Add(new PluginSubLogPrinter(parent.logName, subName));
  120. if (logThread == null || !logThread.IsAlive)
  121. {
  122. logThread = new Thread(LogThread);
  123. logThread.Start();
  124. }
  125. }
  126. internal StandardLogger(string name)
  127. {
  128. ConsoleColorSupport();
  129. if (!finalizedDefaultPrinters)
  130. {
  131. if (!addedConsolePrinters)
  132. AddDefaultPrinter(new ColorlessConsolePrinter());
  133. finalizedDefaultPrinters = true;
  134. }
  135. logName = name;
  136. printers.Add(new PluginLogFilePrinter(name));
  137. if (logThread == null || !logThread.IsAlive)
  138. {
  139. logThread = new Thread(LogThread);
  140. logThread.Start();
  141. }
  142. }
  143. /// <summary>
  144. /// Gets a child printer with the given name, either constructing a new one or using one that was already made.
  145. /// </summary>
  146. /// <param name="name"></param>
  147. /// <returns>a child <see cref="StandardLogger"/> with the given sub-name</returns>
  148. internal StandardLogger GetChild(string name)
  149. {
  150. if (!children.TryGetValue(name, out var child))
  151. {
  152. child = new StandardLogger(this, name);
  153. children.Add(name, child);
  154. }
  155. return child;
  156. }
  157. /// <summary>
  158. /// Adds a log printer to the logger.
  159. /// </summary>
  160. /// <param name="printer">the printer to add</param>
  161. public void AddPrinter(LogPrinter printer)
  162. {
  163. printers.Add(printer);
  164. }
  165. /// <summary>
  166. /// Logs a specific message at a given level.
  167. /// </summary>
  168. /// <param name="level">the message level</param>
  169. /// <param name="message">the message to log</param>
  170. public override void Log(Level level, string message)
  171. {
  172. if (message == null)
  173. throw new ArgumentNullException(nameof(message));
  174. if (!showTrace && level == Level.Trace) return;
  175. // make sure that the queue isn't being cleared
  176. logWaitEvent.Wait();
  177. logQueue.Add(new LogMessage
  178. {
  179. Level = level,
  180. Message = message,
  181. Logger = this,
  182. Time = Utils.CurrentTime()
  183. });
  184. }
  185. /// <inheritdoc />
  186. /// <summary>
  187. /// An override to <see cref="M:IPA.Logging.Logger.Debug(System.String)" /> which shows the method that called it.
  188. /// </summary>
  189. /// <param name="message">the message to log</param>
  190. public override void Debug(string message)
  191. {
  192. if (showSourceClass)
  193. {
  194. // add source to message
  195. var stackFrame = new StackTrace(true).GetFrame(1);
  196. var lineNo = stackFrame.GetFileLineNumber();
  197. if (lineNo == 0)
  198. { // no debug info
  199. var method = stackFrame.GetMethod();
  200. var paramString = string.Join(", ", method.GetParameters().Select(p => p.ParameterType.FullName).StrJP());
  201. message = $"{{{method.DeclaringType?.FullName}::{method.Name}({paramString})}} {message}";
  202. }
  203. else
  204. message = $"{{{stackFrame.GetFileName()}:{lineNo}}} {message}";
  205. }
  206. base.Debug(message);
  207. }
  208. private struct LogMessage
  209. {
  210. public Level Level;
  211. public StandardLogger Logger;
  212. public string Message;
  213. public DateTime Time;
  214. }
  215. private static ManualResetEventSlim logWaitEvent = new ManualResetEventSlim(true);
  216. private static readonly BlockingCollection<LogMessage> logQueue = new BlockingCollection<LogMessage>();
  217. private static Thread logThread;
  218. private static StandardLogger loggerLogger;
  219. private const int LogCloseTimeout = 250;
  220. /// <summary>
  221. /// The log printer thread for <see cref="StandardLogger"/>.
  222. /// </summary>
  223. private static void LogThread()
  224. {
  225. AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
  226. {
  227. StopLogThread();
  228. };
  229. loggerLogger = new StandardLogger("Log Subsystem");
  230. loggerLogger.printers.Clear(); // don't need a log file for this one
  231. var timeout = TimeSpan.FromMilliseconds(LogCloseTimeout);
  232. var started = new HashSet<LogPrinter>();
  233. while (logQueue.TryTake(out var msg, Timeout.Infinite))
  234. {
  235. StdoutInterceptor.Intercept(); // only runs once, after the first message is queued
  236. do
  237. {
  238. var logger = msg.Logger;
  239. IEnumerable<LogPrinter> printers = logger.printers;
  240. do
  241. { // aggregate all printers in the inheritance chain
  242. logger = logger.parent;
  243. if (logger != null)
  244. printers = printers.Concat(logger.printers);
  245. } while (logger != null);
  246. foreach (var printer in printers.Concat(defaultPrinters))
  247. {
  248. try
  249. { // print to them all
  250. if (((byte) msg.Level & (byte) printer.Filter) != 0)
  251. {
  252. if (!started.Contains(printer))
  253. { // start printer if not started
  254. printer.StartPrint();
  255. started.Add(printer);
  256. }
  257. // update last use time and print
  258. printer.LastUse = Utils.CurrentTime();
  259. printer.Print(msg.Level, msg.Time, msg.Logger.logName, msg.Message);
  260. }
  261. }
  262. catch (Exception e)
  263. {
  264. // do something sane in the face of an error
  265. Console.WriteLine($"printer errored: {e}");
  266. }
  267. }
  268. var debugConfig = SelfConfig.Instance?.Debug;
  269. if (debugConfig != null && debugConfig.HideMessagesForPerformance
  270. && logQueue.Count > debugConfig.HideLogThreshold)
  271. { // spam filtering (if queue has more than HideLogThreshold elements)
  272. logWaitEvent.Reset(); // pause incoming log requests
  273. // clear loggers for this instance, to print the message to all affected logs
  274. loggerLogger.printers.Clear();
  275. var prints = new HashSet<LogPrinter>();
  276. // clear the queue
  277. while (logQueue.TryTake(out var message))
  278. { // aggregate loggers in the process
  279. var messageLogger = message.Logger;
  280. foreach (var print in messageLogger.printers)
  281. prints.Add(print);
  282. do
  283. {
  284. messageLogger = messageLogger.parent;
  285. if (messageLogger != null)
  286. foreach (var print in messageLogger.printers)
  287. prints.Add(print);
  288. } while (messageLogger != null);
  289. }
  290. // print using logging subsystem to all logger printers
  291. loggerLogger.printers.AddRange(prints);
  292. logQueue.Add(new LogMessage
  293. { // manually adding to the queue instead of using Warn() because calls to the logger are suspended here
  294. Level = Level.Warning,
  295. Logger = loggerLogger,
  296. Message = $"{loggerLogger.logName.ToUpper()}: Messages omitted to improve performance",
  297. Time = Utils.CurrentTime()
  298. });
  299. // resume log calls
  300. logWaitEvent.Set();
  301. }
  302. var now = Utils.CurrentTime();
  303. var copy = new List<LogPrinter>(started);
  304. foreach (var printer in copy)
  305. {
  306. // close printer after 500ms from its last use
  307. if (now - printer.LastUse > timeout)
  308. {
  309. try
  310. {
  311. printer.EndPrint();
  312. }
  313. catch (Exception e)
  314. {
  315. Console.WriteLine($"printer errored: {e}");
  316. }
  317. started.Remove(printer);
  318. }
  319. }
  320. }
  321. // wait for messages for 500ms before ending the prints
  322. while (logQueue.TryTake(out msg, timeout));
  323. if (logQueue.Count == 0)
  324. { // when the queue has been empty for 500ms, end all prints
  325. foreach (var printer in started)
  326. {
  327. try
  328. {
  329. printer.EndPrint();
  330. }
  331. catch (Exception e)
  332. {
  333. Console.WriteLine($"printer errored: {e}");
  334. }
  335. }
  336. started.Clear();
  337. }
  338. }
  339. }
  340. /// <summary>
  341. /// Stops and joins the log printer thread.
  342. /// </summary>
  343. internal static void StopLogThread()
  344. {
  345. logQueue.CompleteAdding();
  346. logThread.Join();
  347. }
  348. }
  349. /// <summary>
  350. /// A class providing extensions for various loggers.
  351. /// </summary>
  352. public static class LoggerExtensions
  353. {
  354. /// <summary>
  355. /// Gets a child logger, if supported. Currently the only defined and supported logger is <see cref="StandardLogger"/>, and most plugins will only ever receive this anyway.
  356. /// </summary>
  357. /// <param name="logger">the parent <see cref="Logger"/></param>
  358. /// <param name="name">the name of the child</param>
  359. /// <returns>the child logger</returns>
  360. public static Logger GetChildLogger(this Logger logger, string name)
  361. {
  362. if (logger is StandardLogger standardLogger)
  363. return standardLogger.GetChild(name);
  364. throw new InvalidOperationException();
  365. }
  366. }
  367. }