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.

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