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.

422 lines
17 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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. // FIXME: trace doesn't seem to ever actually appear
  175. if (!showTrace && level == Level.Trace) return;
  176. // make sure that the queue isn't being cleared
  177. logWaitEvent.Wait();
  178. logQueue.Add(new LogMessage
  179. {
  180. Level = level,
  181. Message = message,
  182. Logger = this,
  183. Time = Utils.CurrentTime()
  184. });
  185. }
  186. /// <inheritdoc />
  187. /// <summary>
  188. /// An override to <see cref="M:IPA.Logging.Logger.Debug(System.String)" /> which shows the method that called it.
  189. /// </summary>
  190. /// <param name="message">the message to log</param>
  191. public override void Debug(string message)
  192. {
  193. if (showSourceClass)
  194. {
  195. // add source to message
  196. var stackFrame = new StackTrace(true).GetFrame(1);
  197. var lineNo = stackFrame.GetFileLineNumber();
  198. if (lineNo == 0)
  199. { // no debug info
  200. var method = stackFrame.GetMethod();
  201. var paramString = string.Join(", ", method.GetParameters().Select(p => p.ParameterType.FullName).StrJP());
  202. message = $"{{{method.DeclaringType?.FullName}::{method.Name}({paramString})}} {message}";
  203. }
  204. else
  205. message = $"{{{stackFrame.GetFileName()}:{lineNo}}} {message}";
  206. }
  207. base.Debug(message);
  208. }
  209. private struct LogMessage
  210. {
  211. public Level Level;
  212. public StandardLogger Logger;
  213. public string Message;
  214. public DateTime Time;
  215. }
  216. private static ManualResetEventSlim logWaitEvent = new ManualResetEventSlim(true);
  217. private static readonly BlockingCollection<LogMessage> logQueue = new BlockingCollection<LogMessage>();
  218. private static Thread logThread;
  219. private static StandardLogger loggerLogger;
  220. private const int LogCloseTimeout = 250;
  221. /// <summary>
  222. /// The log printer thread for <see cref="StandardLogger"/>.
  223. /// </summary>
  224. private static void LogThread()
  225. {
  226. AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
  227. {
  228. StopLogThread();
  229. };
  230. loggerLogger = new StandardLogger("Log Subsystem");
  231. loggerLogger.printers.Clear(); // don't need a log file for this one
  232. var timeout = TimeSpan.FromMilliseconds(LogCloseTimeout);
  233. try
  234. {
  235. var started = new HashSet<LogPrinter>();
  236. while (logQueue.TryTake(out var msg, Timeout.Infinite))
  237. {
  238. StdoutInterceptor.Intercept(); // only runs once, after the first message is queued
  239. do
  240. {
  241. var logger = msg.Logger;
  242. IEnumerable<LogPrinter> printers = logger.printers;
  243. do
  244. { // aggregate all printers in the inheritance chain
  245. logger = logger.parent;
  246. if (logger != null)
  247. printers = printers.Concat(logger.printers);
  248. } while (logger != null);
  249. foreach (var printer in printers.Concat(defaultPrinters))
  250. {
  251. try
  252. { // print to them all
  253. if (((byte)msg.Level & (byte)printer.Filter) != 0)
  254. {
  255. if (!started.Contains(printer))
  256. { // start printer if not started
  257. printer.StartPrint();
  258. started.Add(printer);
  259. }
  260. // update last use time and print
  261. printer.LastUse = Utils.CurrentTime();
  262. printer.Print(msg.Level, msg.Time, msg.Logger.logName, msg.Message);
  263. }
  264. }
  265. catch (Exception e)
  266. {
  267. // do something sane in the face of an error
  268. Console.WriteLine($"printer errored: {e}");
  269. }
  270. }
  271. var debugConfig = SelfConfig.Instance?.Debug;
  272. if (debugConfig != null && debugConfig.HideMessagesForPerformance
  273. && logQueue.Count > debugConfig.HideLogThreshold)
  274. { // spam filtering (if queue has more than HideLogThreshold elements)
  275. logWaitEvent.Reset(); // pause incoming log requests
  276. // clear loggers for this instance, to print the message to all affected logs
  277. loggerLogger.printers.Clear();
  278. var prints = new HashSet<LogPrinter>();
  279. // clear the queue
  280. while (logQueue.TryTake(out var message))
  281. { // aggregate loggers in the process
  282. var messageLogger = message.Logger;
  283. foreach (var print in messageLogger.printers)
  284. prints.Add(print);
  285. do
  286. {
  287. messageLogger = messageLogger.parent;
  288. if (messageLogger != null)
  289. foreach (var print in messageLogger.printers)
  290. prints.Add(print);
  291. } while (messageLogger != null);
  292. }
  293. // print using logging subsystem to all logger printers
  294. loggerLogger.printers.AddRange(prints);
  295. logQueue.Add(new LogMessage
  296. { // manually adding to the queue instead of using Warn() because calls to the logger are suspended here
  297. Level = Level.Warning,
  298. Logger = loggerLogger,
  299. Message = $"{loggerLogger.logName.ToUpper()}: Messages omitted to improve performance",
  300. Time = Utils.CurrentTime()
  301. });
  302. // resume log calls
  303. logWaitEvent.Set();
  304. }
  305. var now = Utils.CurrentTime();
  306. var copy = new List<LogPrinter>(started);
  307. foreach (var printer in copy)
  308. {
  309. // close printer after 500ms from its last use
  310. if (now - printer.LastUse > timeout)
  311. {
  312. try
  313. {
  314. printer.EndPrint();
  315. }
  316. catch (Exception e)
  317. {
  318. Console.WriteLine($"printer errored: {e}");
  319. }
  320. started.Remove(printer);
  321. }
  322. }
  323. }
  324. // wait for messages for 500ms before ending the prints
  325. while (logQueue.TryTake(out msg, timeout));
  326. if (logQueue.Count == 0)
  327. { // when the queue has been empty for 500ms, end all prints
  328. foreach (var printer in started)
  329. {
  330. try
  331. {
  332. printer.EndPrint();
  333. }
  334. catch (Exception e)
  335. {
  336. Console.WriteLine($"printer errored: {e}");
  337. }
  338. }
  339. started.Clear();
  340. }
  341. }
  342. }
  343. catch (InvalidOperationException)
  344. {
  345. }
  346. }
  347. /// <summary>
  348. /// Stops and joins the log printer thread.
  349. /// </summary>
  350. internal static void StopLogThread()
  351. {
  352. logQueue.CompleteAdding();
  353. logThread.Join();
  354. }
  355. }
  356. /// <summary>
  357. /// A class providing extensions for various loggers.
  358. /// </summary>
  359. public static class LoggerExtensions
  360. {
  361. /// <summary>
  362. /// 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.
  363. /// </summary>
  364. /// <param name="logger">the parent <see cref="Logger"/></param>
  365. /// <param name="name">the name of the child</param>
  366. /// <returns>the child logger</returns>
  367. public static Logger GetChildLogger(this Logger logger, string name)
  368. {
  369. if (logger is StandardLogger standardLogger)
  370. return standardLogger.GetChild(name);
  371. throw new InvalidOperationException();
  372. }
  373. }
  374. }