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