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.

416 lines
16 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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; 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. /// <param name="cfg"></param>
  108. internal static void Configure(SelfConfig cfg)
  109. {
  110. showSourceClass = SelfConfig.Debug_.ShowCallSource_;
  111. PrintFilter = SelfConfig.Debug_.ShowDebug_ ? LogLevel.All : LogLevel.InfoUp;
  112. showTrace = SelfConfig.Debug_.ShowTrace_;
  113. }
  114. private StandardLogger(StandardLogger parent, string subName)
  115. {
  116. logName = $"{parent.logName}/{subName}";
  117. this.parent = parent;
  118. printers = new List<LogPrinter>();
  119. if (!SelfConfig.Debug_.CondenseModLogs_)
  120. printers.Add(new PluginSubLogPrinter(parent.logName, subName));
  121. if (logThread == null || !logThread.IsAlive)
  122. {
  123. logThread = new Thread(LogThread);
  124. logThread.Start();
  125. }
  126. }
  127. internal StandardLogger(string name)
  128. {
  129. ConsoleColorSupport();
  130. if (!finalizedDefaultPrinters)
  131. {
  132. if (!addedConsolePrinters)
  133. AddDefaultPrinter(new ColorlessConsolePrinter());
  134. finalizedDefaultPrinters = true;
  135. }
  136. logName = name;
  137. printers.Add(new PluginLogFilePrinter(name));
  138. if (logThread == null || !logThread.IsAlive)
  139. {
  140. logThread = new Thread(LogThread);
  141. logThread.Start();
  142. }
  143. }
  144. /// <summary>
  145. /// Gets a child printer with the given name, either constructing a new one or using one that was already made.
  146. /// </summary>
  147. /// <param name="name"></param>
  148. /// <returns>a child <see cref="StandardLogger"/> with the given sub-name</returns>
  149. internal StandardLogger GetChild(string name)
  150. {
  151. if (!children.TryGetValue(name, out var child))
  152. {
  153. child = new StandardLogger(this, name);
  154. children.Add(name, child);
  155. }
  156. return child;
  157. }
  158. /// <summary>
  159. /// Adds a log printer to the logger.
  160. /// </summary>
  161. /// <param name="printer">the printer to add</param>
  162. public void AddPrinter(LogPrinter printer)
  163. {
  164. printers.Add(printer);
  165. }
  166. /// <summary>
  167. /// Logs a specific message at a given level.
  168. /// </summary>
  169. /// <param name="level">the message level</param>
  170. /// <param name="message">the message to log</param>
  171. public override void Log(Level level, string message)
  172. {
  173. if (message == null)
  174. throw new ArgumentNullException(nameof(message));
  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. var started = new HashSet<LogPrinter>();
  234. while (logQueue.TryTake(out var msg, Timeout.Infinite))
  235. {
  236. StdoutInterceptor.Intercept(); // only runs once, after the first message is queued
  237. do
  238. {
  239. var logger = msg.Logger;
  240. IEnumerable<LogPrinter> printers = logger.printers;
  241. do
  242. { // aggregate all printers in the inheritance chain
  243. logger = logger.parent;
  244. if (logger != null)
  245. printers = printers.Concat(logger.printers);
  246. } while (logger != null);
  247. foreach (var printer in printers.Concat(defaultPrinters))
  248. {
  249. try
  250. { // print to them all
  251. if (((byte) msg.Level & (byte) printer.Filter) != 0)
  252. {
  253. if (!started.Contains(printer))
  254. { // start printer if not started
  255. printer.StartPrint();
  256. started.Add(printer);
  257. }
  258. // update last use time and print
  259. printer.LastUse = Utils.CurrentTime();
  260. printer.Print(msg.Level, msg.Time, msg.Logger.logName, msg.Message);
  261. }
  262. }
  263. catch (Exception e)
  264. {
  265. // do something sane in the face of an error
  266. Console.WriteLine($"printer errored: {e}");
  267. }
  268. }
  269. var debugConfig = SelfConfig.Instance?.Debug;
  270. if (debugConfig != null && debugConfig.HideMessagesForPerformance
  271. && logQueue.Count > debugConfig.HideLogThreshold)
  272. { // spam filtering (if queue has more than HideLogThreshold elements)
  273. logWaitEvent.Reset(); // pause incoming log requests
  274. // clear loggers for this instance, to print the message to all affected logs
  275. loggerLogger.printers.Clear();
  276. var prints = new HashSet<LogPrinter>();
  277. // clear the queue
  278. while (logQueue.TryTake(out var message))
  279. { // aggregate loggers in the process
  280. var messageLogger = message.Logger;
  281. foreach (var print in messageLogger.printers)
  282. prints.Add(print);
  283. do
  284. {
  285. messageLogger = messageLogger.parent;
  286. if (messageLogger != null)
  287. foreach (var print in messageLogger.printers)
  288. prints.Add(print);
  289. } while (messageLogger != null);
  290. }
  291. // print using logging subsystem to all logger printers
  292. loggerLogger.printers.AddRange(prints);
  293. logQueue.Add(new LogMessage
  294. { // manually adding to the queue instead of using Warn() because calls to the logger are suspended here
  295. Level = Level.Warning,
  296. Logger = loggerLogger,
  297. Message = $"{loggerLogger.logName.ToUpper()}: Messages omitted to improve performance",
  298. Time = Utils.CurrentTime()
  299. });
  300. // resume log calls
  301. logWaitEvent.Set();
  302. }
  303. var now = Utils.CurrentTime();
  304. var copy = new List<LogPrinter>(started);
  305. foreach (var printer in copy)
  306. {
  307. // close printer after 500ms from its last use
  308. if (now - printer.LastUse > timeout)
  309. {
  310. try
  311. {
  312. printer.EndPrint();
  313. }
  314. catch (Exception e)
  315. {
  316. Console.WriteLine($"printer errored: {e}");
  317. }
  318. started.Remove(printer);
  319. }
  320. }
  321. }
  322. // wait for messages for 500ms before ending the prints
  323. while (logQueue.TryTake(out msg, timeout));
  324. if (logQueue.Count == 0)
  325. { // when the queue has been empty for 500ms, end all prints
  326. foreach (var printer in started)
  327. {
  328. try
  329. {
  330. printer.EndPrint();
  331. }
  332. catch (Exception e)
  333. {
  334. Console.WriteLine($"printer errored: {e}");
  335. }
  336. }
  337. started.Clear();
  338. }
  339. }
  340. }
  341. /// <summary>
  342. /// Stops and joins the log printer thread.
  343. /// </summary>
  344. internal static void StopLogThread()
  345. {
  346. logQueue.CompleteAdding();
  347. logThread.Join();
  348. }
  349. }
  350. /// <summary>
  351. /// A class providing extensions for various loggers.
  352. /// </summary>
  353. public static class LoggerExtensions
  354. {
  355. /// <summary>
  356. /// 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.
  357. /// </summary>
  358. /// <param name="logger">the parent <see cref="Logger"/></param>
  359. /// <param name="name">the name of the child</param>
  360. /// <returns>the child logger</returns>
  361. public static Logger GetChildLogger(this Logger logger, string name)
  362. {
  363. if (logger is StandardLogger standardLogger)
  364. return standardLogger.GetChild(name);
  365. throw new InvalidOperationException();
  366. }
  367. }
  368. }