Logger.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. int indent;
  125. if (!_indents.TryGetValue(threadId, out indent))
  126. {
  127. indent = 0;
  128. }
  129. _indents[threadId] = indent + 1;
  130. }
  131. }
  132. public void Unindent()
  133. {
  134. lock (_logLock)
  135. {
  136. int threadId = GetThread();
  137. _indents[threadId]--;
  138. }
  139. }
  140. public void Dispose()
  141. {
  142. lock (_logLock)
  143. {
  144. if (Logging)
  145. {
  146. WriteCounters();
  147. WriteProcesses();
  148. _writter.Dispose();
  149. _writter = null;
  150. }
  151. foreach (PerformanceCounter counter in _performanceCounters)
  152. {
  153. counter.Dispose();
  154. }
  155. }
  156. }
  157. public void WriteCounters()
  158. {
  159. if (Logging && (LogLevel >= 1))
  160. {
  161. try
  162. {
  163. foreach (PerformanceCounter counter in _performanceCounters)
  164. {
  165. WriteLine("{0}{1}{2} = [{3}]",
  166. counter.CounterName,
  167. (string.IsNullOrEmpty(counter.InstanceName) ? string.Empty : "/"),
  168. counter.InstanceName,
  169. counter.NextValue());
  170. }
  171. }
  172. catch (Exception e)
  173. {
  174. WriteLine("Error reading counters: {0}", e);
  175. }
  176. }
  177. }
  178. public void WriteProcesses()
  179. {
  180. if (Logging && (LogLevel >= 1))
  181. {
  182. try
  183. {
  184. Process[] processes = Process.GetProcesses();
  185. foreach (Process process in processes)
  186. {
  187. WriteLine("{0}:{1} - {2} - {3}", process.Id, process.ProcessName, GetProcessStartTime(process), GetTotalProcessorTime(process));
  188. }
  189. }
  190. catch (Exception e)
  191. {
  192. WriteLine("Error logging processes: {0}", e);
  193. }
  194. }
  195. }
  196. private static object GetProcessStartTime(Process process)
  197. {
  198. try
  199. {
  200. return process.StartTime;
  201. }
  202. catch
  203. {
  204. return "???";
  205. }
  206. }
  207. private static object GetTotalProcessorTime(Process process)
  208. {
  209. try
  210. {
  211. return process.TotalProcessorTime;
  212. }
  213. catch
  214. {
  215. return "???";
  216. }
  217. }
  218. public Callstack CreateCallstack(object token = null)
  219. {
  220. return new Callstack(this, token);
  221. }
  222. public Callstack CreateCallstackAndLock()
  223. {
  224. return new CallstackAndLock(this, _lock);
  225. }
  226. public Exception WriteException(Exception e)
  227. {
  228. lock (_logLock)
  229. {
  230. if (Logging)
  231. {
  232. DoWriteLine(string.Format(CultureInfo.CurrentCulture, "Exception: {0}", e));
  233. if (LogLevel >= 1)
  234. {
  235. DoWriteLine(new StackTrace().ToString());
  236. }
  237. }
  238. }
  239. return e;
  240. }
  241. private int GetIndent()
  242. {
  243. int indent;
  244. if (!_indents.TryGetValue(GetThread(), out indent))
  245. {
  246. indent = 0;
  247. }
  248. return indent;
  249. }
  250. private void DoWriteLine(string message)
  251. {
  252. int indent = GetIndent();
  253. string s =
  254. string.Format(CultureInfo.InvariantCulture, "[{0:yyyy-MM-dd HH:mm:ss.fffZ}] [{1:x4}] {2}{3}",
  255. DateTime.Now, Thread.CurrentThread.ManagedThreadId,
  256. (indent > 0 ? new string(' ', indent * 2) : string.Empty), message);
  257. _writter.WriteLine(s);
  258. }
  259. private void SetLogPath(string value)
  260. {
  261. lock (_logLock)
  262. {
  263. if (_logPath != value)
  264. {
  265. Dispose();
  266. _logPath = value;
  267. if (!string.IsNullOrEmpty(_logPath))
  268. {
  269. _writter = File.CreateText(_logPath);
  270. _writter.AutoFlush = true;
  271. WriteEnvironmentInfo();
  272. if (_logLevel >= 1)
  273. {
  274. CreateCounters();
  275. }
  276. }
  277. }
  278. }
  279. }
  280. private void WriteEnvironmentInfo()
  281. {
  282. Assembly assembly = Assembly.GetExecutingAssembly();
  283. WriteLine("Executing assembly: {0}", assembly);
  284. WriteLine("Executing assembly codebase: {0}", (assembly.CodeBase ?? "unknown"));
  285. WriteLine("Executing assembly location: {0}", (assembly.Location ?? "unknown"));
  286. Assembly entryAssembly = Assembly.GetEntryAssembly();
  287. WriteLine("Entry Assembly: {0}", (entryAssembly != null ? entryAssembly.ToString() : "unmanaged"));
  288. WriteLine("Operating system: {0}", Environment.OSVersion);
  289. WriteLine("User: {0}@{1}@{2}; Interactive: {3}", Environment.UserName, Environment.UserDomainName, Environment.MachineName, Environment.UserInteractive);
  290. WriteLine("Runtime: {0}", Environment.Version);
  291. WriteLine("Console encoding: Input: {0} ({1}); Output: {2} ({3})", Console.InputEncoding.EncodingName, Console.InputEncoding.CodePage, Console.OutputEncoding.EncodingName, Console.OutputEncoding.CodePage);
  292. WriteLine("Working directory: {0}", Environment.CurrentDirectory);
  293. string path = GetAssemblyFilePath();
  294. FileVersionInfo version = string.IsNullOrEmpty(path) ? null : FileVersionInfo.GetVersionInfo(path);
  295. WriteLine("Assembly path: {0}", path);
  296. WriteLine("Assembly product version: {0}", ((version != null) ? version.ProductVersion : "unknown"));
  297. }
  298. public static string LastWin32ErrorMessage()
  299. {
  300. return new Win32Exception(Marshal.GetLastWin32Error()).Message;
  301. }
  302. private void SetLogLevel(int value)
  303. {
  304. if ((value < 0) || (value > 2))
  305. {
  306. throw WriteException(new ArgumentOutOfRangeException(string.Format(CultureInfo.CurrentCulture, "Logging level has to be in range 0-2")));
  307. }
  308. _logLevel = value;
  309. }
  310. private StreamWriter _writter;
  311. private string _logPath;
  312. private readonly Dictionary<int, int> _indents = new Dictionary<int, int>();
  313. private readonly object _logLock = new object();
  314. private readonly Lock _lock = new Lock();
  315. private List<PerformanceCounter> _performanceCounters = new List<PerformanceCounter>();
  316. private int _logLevel;
  317. }
  318. }