Logger.cs 14 KB

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