Logger.cs 12 KB

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