Logger.cs 12 KB

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