Logger.cs 11 KB

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