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.

408 lines
15 KiB

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