Logger.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Reflection;
  6. using System.Diagnostics;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Runtime.InteropServices;
  10. namespace WinSCP
  11. {
  12. internal class Logger : IDisposable
  13. {
  14. public string LogPath { get { return _logPath; } set { SetLogPath(value); } }
  15. public int LogLevel { get { return _logLevel; } set { SetLogLevel(value); } }
  16. public bool Logging { get { return (_writter != null) && _writter.BaseStream.CanWrite; } }
  17. public Lock Lock { get; } = new Lock();
  18. public string GetAssemblyFilePath()
  19. {
  20. Assembly assembly = Assembly.GetExecutingAssembly();
  21. return DoGetAssemblyFilePath(assembly);
  22. }
  23. public string GetEntryAssemblyFilePath()
  24. {
  25. Assembly assembly = Assembly.GetEntryAssembly();
  26. return (assembly != null) ? DoGetAssemblyFilePath(assembly) : null;
  27. }
  28. private string DoGetAssemblyFilePath(Assembly assembly)
  29. {
  30. string path = null;
  31. // https://docs.microsoft.com/en-us/archive/blogs/suzcook/assembly-codebase-vs-assembly-location
  32. // The CodeBase is a URL to the place where the file was found,
  33. // while the Location is the path from where it was actually loaded.
  34. // For example, if the assembly was downloaded from the internet, its CodeBase may start with "http://",
  35. // but its Location may start with "C:\".
  36. // If the file was shadow copied, the Location would be the path to the copy of the file in the shadow-copy dir.
  37. // It's also good to know that the CodeBase is not guaranteed to be set for assemblies in the GAC.
  38. // Location will always be set for assemblies loaded from disk, however.
  39. string codeBase = assembly.CodeBase;
  40. string location = assembly.Location;
  41. // cannot use Uri.UnescapeDataString, because it treats some characters valid in
  42. // local path (like #) specially
  43. const string protocol = "file://";
  44. if (codeBase.StartsWith(protocol, StringComparison.OrdinalIgnoreCase))
  45. {
  46. path = codeBase.Substring(protocol.Length).Replace('/', '\\');
  47. if (!string.IsNullOrEmpty(path))
  48. {
  49. if (path[0] == '\\')
  50. {
  51. path = path.Substring(1, path.Length - 1);
  52. }
  53. else
  54. {
  55. // UNC path
  56. path = @"\\" + path;
  57. }
  58. }
  59. }
  60. if (string.IsNullOrEmpty(path) || !File.Exists(path))
  61. {
  62. if (File.Exists(location))
  63. {
  64. path = location;
  65. }
  66. else
  67. {
  68. WriteLine(
  69. string.Format(
  70. CultureInfo.CurrentCulture,
  71. "Cannot locate path of assembly [{0}] neither from its code base [{1}], nor from its location [{2}]",
  72. assembly, codeBase, location));
  73. path = null;
  74. }
  75. }
  76. return path;
  77. }
  78. #if !NETSTANDARD
  79. private void CreateCounters()
  80. {
  81. try
  82. {
  83. PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();
  84. foreach (PerformanceCounterCategory category in categories)
  85. {
  86. if (category.CategoryName == "Processor")
  87. {
  88. string[] instances = category.GetInstanceNames();
  89. foreach (string instance in instances)
  90. {
  91. AddCounter(new PerformanceCounter(category.CategoryName, "% Processor Time", instance));
  92. }
  93. }
  94. }
  95. AddCounter(new PerformanceCounter("Memory", "Available KBytes"));
  96. }
  97. catch (UnauthorizedAccessException)
  98. {
  99. WriteLine("Not authorized to get counters");
  100. }
  101. catch (Exception e)
  102. {
  103. WriteLine("Error getting counters: {0}", e);
  104. }
  105. }
  106. private void AddCounter(PerformanceCounter counter)
  107. {
  108. counter.NextValue();
  109. _performanceCounters.Add(counter);
  110. }
  111. #endif
  112. public void WriteLine(string line)
  113. {
  114. lock (_logLock)
  115. {
  116. if (Logging)
  117. {
  118. DoWriteLine(line);
  119. }
  120. }
  121. }
  122. public void WriteLine(string format, params object[] args)
  123. {
  124. lock (_logLock)
  125. {
  126. if (Logging)
  127. {
  128. DoWriteLine(string.Format(CultureInfo.CurrentCulture, format, args));
  129. }
  130. }
  131. }
  132. public void WriteLineLevel(int level, string line)
  133. {
  134. if (LogLevel >= level)
  135. {
  136. WriteLine(line);
  137. }
  138. }
  139. public void WriteLineLevel(int level, string line, params object[] args)
  140. {
  141. if (LogLevel >= level)
  142. {
  143. WriteLine(line, args);
  144. }
  145. }
  146. private static int GetThread()
  147. {
  148. return Thread.CurrentThread.ManagedThreadId;
  149. }
  150. public void Indent()
  151. {
  152. lock (_logLock)
  153. {
  154. int threadId = GetThread();
  155. if (!_indents.TryGetValue(threadId, out int indent))
  156. {
  157. indent = 0;
  158. }
  159. _indents[threadId] = indent + 1;
  160. }
  161. }
  162. public void Unindent()
  163. {
  164. lock (_logLock)
  165. {
  166. int threadId = GetThread();
  167. _indents[threadId]--;
  168. }
  169. }
  170. public void Dispose()
  171. {
  172. lock (_logLock)
  173. {
  174. if (Logging)
  175. {
  176. #if !NETSTANDARD
  177. WriteCounters();
  178. #endif
  179. WriteProcesses();
  180. _writter.Dispose();
  181. _writter = null;
  182. }
  183. #if !NETSTANDARD
  184. foreach (PerformanceCounter counter in _performanceCounters)
  185. {
  186. counter.Dispose();
  187. }
  188. #endif
  189. }
  190. }
  191. #if !NETSTANDARD
  192. public void WriteCounters()
  193. {
  194. if (Logging && (LogLevel >= 1))
  195. {
  196. try
  197. {
  198. foreach (PerformanceCounter counter in _performanceCounters)
  199. {
  200. WriteLine("{0}{1}{2} = [{3}]",
  201. counter.CounterName,
  202. (string.IsNullOrEmpty(counter.InstanceName) ? string.Empty : "/"),
  203. counter.InstanceName,
  204. counter.NextValue());
  205. }
  206. }
  207. catch (Exception e)
  208. {
  209. WriteLine("Error reading counters: {0}", e);
  210. }
  211. }
  212. }
  213. #endif
  214. public void WriteProcesses()
  215. {
  216. if (Logging && (LogLevel >= 1))
  217. {
  218. try
  219. {
  220. Process[] processes = Process.GetProcesses();
  221. foreach (Process process in processes)
  222. {
  223. WriteLine("{0}:{1} - {2} - {3}", process.Id, process.ProcessName, GetProcessStartTime(process), GetTotalProcessorTime(process));
  224. }
  225. }
  226. catch (Exception e)
  227. {
  228. WriteLine("Error logging processes: {0}", e);
  229. }
  230. }
  231. }
  232. private static object GetProcessStartTime(Process process)
  233. {
  234. try
  235. {
  236. return process.StartTime;
  237. }
  238. catch
  239. {
  240. return "???";
  241. }
  242. }
  243. private static object GetTotalProcessorTime(Process process)
  244. {
  245. try
  246. {
  247. return process.TotalProcessorTime;
  248. }
  249. catch
  250. {
  251. return "???";
  252. }
  253. }
  254. public Callstack CreateCallstack(object token = null)
  255. {
  256. return new Callstack(this, token);
  257. }
  258. public CallstackAndLock CreateCallstackAndLock()
  259. {
  260. return new CallstackAndLock(this, Lock);
  261. }
  262. public Exception WriteException(Exception e)
  263. {
  264. lock (_logLock)
  265. {
  266. if (Logging)
  267. {
  268. DoWriteLine(string.Format(CultureInfo.CurrentCulture, "Exception: {0}", e));
  269. if (LogLevel >= 1)
  270. {
  271. DoWriteLine(new StackTrace().ToString());
  272. }
  273. }
  274. }
  275. return e;
  276. }
  277. private int GetIndent()
  278. {
  279. if (!_indents.TryGetValue(GetThread(), out int indent))
  280. {
  281. indent = 0;
  282. }
  283. return indent;
  284. }
  285. private void DoWriteLine(string message)
  286. {
  287. int indent = GetIndent();
  288. string s =
  289. string.Format(CultureInfo.InvariantCulture, "[{0:yyyy-MM-dd HH:mm:ss.fff}] [{1:x4}] {2}{3}",
  290. DateTime.Now, Thread.CurrentThread.ManagedThreadId,
  291. (indent > 0 ? new string(' ', indent * 2) : string.Empty), message);
  292. _writter.WriteLine(s);
  293. }
  294. private void SetLogPath(string value)
  295. {
  296. lock (_logLock)
  297. {
  298. if (_logPath != value)
  299. {
  300. Dispose();
  301. _logPath = value;
  302. if (!string.IsNullOrEmpty(_logPath))
  303. {
  304. _writter = File.CreateText(_logPath);
  305. _writter.AutoFlush = true;
  306. WriteEnvironmentInfo();
  307. #if !NETSTANDARD
  308. if (_logLevel >= 1)
  309. {
  310. CreateCounters();
  311. }
  312. #endif
  313. }
  314. }
  315. }
  316. }
  317. private void WriteEnvironmentInfo()
  318. {
  319. Assembly assembly = Assembly.GetExecutingAssembly();
  320. #if NETSTANDARD
  321. WriteLine(".NET Standard build");
  322. #else
  323. WriteLine(".NET Framework build");
  324. #endif
  325. WriteLine("Executing assembly: {0}", assembly);
  326. WriteLine("Executing assembly codebase: {0}", (assembly.CodeBase ?? "unknown"));
  327. WriteLine("Executing assembly location: {0}", (assembly.Location ?? "unknown"));
  328. Assembly entryAssembly = Assembly.GetEntryAssembly();
  329. WriteLine("Entry Assembly: {0}", (entryAssembly != null ? entryAssembly.ToString() : "unmanaged"));
  330. WriteLine("Operating system: {0}", Environment.OSVersion);
  331. #if NETSTANDARD
  332. WriteLine("Operating system information: {0} {1} {2}", RuntimeInformation.OSDescription, RuntimeInformation.OSArchitecture, RuntimeInformation.ProcessArchitecture);
  333. #endif
  334. TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
  335. WriteLine(
  336. "Timezone: {0}; {1}",
  337. ((offset > TimeSpan.Zero ? "+" : (offset < TimeSpan.Zero ? "-" : string.Empty)) + offset.ToString("hh\\:mm")),
  338. (TimeZoneInfo.Local.IsDaylightSavingTime(DateTime.Now) ? TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName));
  339. WriteLine("User: {0}@{1}@{2}; Interactive: {3}", Environment.UserName, Environment.UserDomainName, Environment.MachineName, Environment.UserInteractive);
  340. WriteLine("Runtime: {0}", Environment.Version);
  341. #if NETSTANDARD
  342. WriteLine("Framework description: {0}", RuntimeInformation.FrameworkDescription);
  343. #endif
  344. WriteLine("Console encoding: Input: {0} ({1}); Output: {2} ({3})", Console.InputEncoding.EncodingName, Console.InputEncoding.CodePage, Console.OutputEncoding.EncodingName, Console.OutputEncoding.CodePage);
  345. WriteLine("Working directory: {0}", Environment.CurrentDirectory);
  346. string path = GetAssemblyFilePath();
  347. FileVersionInfo version = string.IsNullOrEmpty(path) ? null : FileVersionInfo.GetVersionInfo(path);
  348. WriteLine("Assembly path: {0}", path);
  349. WriteLine("Assembly product version: {0}", ((version != null) ? version.ProductVersion : "unknown"));
  350. if (Assembly.GetEntryAssembly() != null)
  351. {
  352. WriteLine("Entry assembly path: {0}", GetEntryAssemblyFilePath());
  353. }
  354. }
  355. public static string LastWin32ErrorMessage()
  356. {
  357. return new Win32Exception(Marshal.GetLastWin32Error()).Message;
  358. }
  359. private void SetLogLevel(int value)
  360. {
  361. if ((value < -1) || (value > 2))
  362. {
  363. throw WriteException(new ArgumentOutOfRangeException(string.Format(CultureInfo.CurrentCulture, "Logging level has to be in range 0-2")));
  364. }
  365. _logLevel = value;
  366. }
  367. private StreamWriter _writter;
  368. private string _logPath;
  369. private readonly Dictionary<int, int> _indents = new Dictionary<int, int>();
  370. private readonly object _logLock = new object();
  371. #if !NETSTANDARD
  372. private readonly List<PerformanceCounter> _performanceCounters = new List<PerformanceCounter>();
  373. #endif
  374. private int _logLevel;
  375. }
  376. }