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.

411 lines
16 KiB

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