1
0

Logger.cs 14 KB

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