Logger.cs 15 KB

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