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.

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