Logger.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 bool Logging { get { return (_writter != null) && _writter.BaseStream.CanWrite; } }
  16. public string GetAssemblyFilePath()
  17. {
  18. Assembly assembly = Assembly.GetExecutingAssembly();
  19. string path = null;
  20. string codeBase = assembly.CodeBase;
  21. string location = assembly.Location;
  22. // cannot use Uri.UnescapeDataString, because it treats some characters valid in
  23. // local path (like #) specially
  24. const string protocol = "file:///";
  25. if (codeBase.StartsWith(protocol, StringComparison.OrdinalIgnoreCase))
  26. {
  27. path =
  28. codeBase.Substring(protocol.Length).Replace('/', '\\');
  29. }
  30. if ((path == null) || !File.Exists(path))
  31. {
  32. if (File.Exists(location))
  33. {
  34. path = location;
  35. }
  36. else
  37. {
  38. WriteLine(
  39. string.Format(
  40. CultureInfo.CurrentCulture,
  41. "Cannot locate path of assembly [{0}] neither from its code base [{1}], nor from its location [{2}]",
  42. assembly, codeBase, location));
  43. path = null;
  44. }
  45. }
  46. return path;
  47. }
  48. private void CreateCounters()
  49. {
  50. try
  51. {
  52. PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();
  53. foreach (PerformanceCounterCategory category in categories)
  54. {
  55. if (category.CategoryName == "Processor")
  56. {
  57. string[] instances = category.GetInstanceNames();
  58. foreach (string instance in instances)
  59. {
  60. AddCounter(new PerformanceCounter(category.CategoryName, "% Processor Time", instance));
  61. }
  62. }
  63. }
  64. AddCounter(new PerformanceCounter("Memory", "Available KBytes"));
  65. }
  66. catch (UnauthorizedAccessException)
  67. {
  68. WriteLine("Not authorized to get counters");
  69. }
  70. catch (Exception e)
  71. {
  72. WriteLine("Error getting counters: {0}", e);
  73. }
  74. }
  75. private void AddCounter(PerformanceCounter counter)
  76. {
  77. counter.NextValue();
  78. _performanceCounters.Add(counter);
  79. }
  80. public void WriteLine(string message)
  81. {
  82. lock (_logLock)
  83. {
  84. if (Logging)
  85. {
  86. DoWriteLine(message);
  87. }
  88. }
  89. }
  90. public void WriteLine(string format, params object[] args)
  91. {
  92. lock (_logLock)
  93. {
  94. if (Logging)
  95. {
  96. DoWriteLine(string.Format(CultureInfo.CurrentCulture, format, args));
  97. }
  98. }
  99. }
  100. private static int GetThread()
  101. {
  102. return Thread.CurrentThread.ManagedThreadId;
  103. }
  104. public void Indent()
  105. {
  106. lock (_logLock)
  107. {
  108. int threadId = GetThread();
  109. int indent;
  110. if (!_indents.TryGetValue(threadId, out indent))
  111. {
  112. indent = 0;
  113. }
  114. _indents[threadId] = indent + 1;
  115. }
  116. }
  117. public void Unindent()
  118. {
  119. lock (_logLock)
  120. {
  121. int threadId = GetThread();
  122. _indents[threadId]--;
  123. }
  124. }
  125. public void Dispose()
  126. {
  127. lock (_logLock)
  128. {
  129. if (Logging)
  130. {
  131. WriteCounters();
  132. WriteProcesses();
  133. _writter.Dispose();
  134. _writter = null;
  135. }
  136. foreach (PerformanceCounter counter in _performanceCounters)
  137. {
  138. counter.Dispose();
  139. }
  140. }
  141. }
  142. public void WriteCounters()
  143. {
  144. if (Logging)
  145. {
  146. try
  147. {
  148. foreach (PerformanceCounter counter in _performanceCounters)
  149. {
  150. WriteLine("{0}{1}{2} = [{3}]",
  151. counter.CounterName,
  152. (string.IsNullOrEmpty(counter.InstanceName) ? string.Empty : "/"),
  153. counter.InstanceName,
  154. counter.NextValue());
  155. }
  156. }
  157. catch (Exception e)
  158. {
  159. WriteLine("Error reading counters: {0}", e);
  160. }
  161. }
  162. }
  163. public void WriteProcesses()
  164. {
  165. if (Logging)
  166. {
  167. try
  168. {
  169. Process[] processes = Process.GetProcesses();
  170. foreach (Process process in processes)
  171. {
  172. WriteLine("{0}:{1} - {2} - {3}", process.Id, process.ProcessName, GetProcessStartTime(process), GetTotalProcessorTime(process));
  173. }
  174. }
  175. catch (Exception e)
  176. {
  177. WriteLine("Error logging processes: {0}", e);
  178. }
  179. }
  180. }
  181. private static object GetProcessStartTime(Process process)
  182. {
  183. try
  184. {
  185. return process.StartTime;
  186. }
  187. catch
  188. {
  189. return "???";
  190. }
  191. }
  192. private static object GetTotalProcessorTime(Process process)
  193. {
  194. try
  195. {
  196. return process.TotalProcessorTime;
  197. }
  198. catch
  199. {
  200. return "???";
  201. }
  202. }
  203. public Callstack CreateCallstack()
  204. {
  205. return new Callstack(this);
  206. }
  207. public Callstack CreateCallstackAndLock()
  208. {
  209. return new CallstackAndLock(this, _lock);
  210. }
  211. private int GetIndent()
  212. {
  213. int indent;
  214. if (!_indents.TryGetValue(GetThread(), out indent))
  215. {
  216. indent = 0;
  217. }
  218. return indent;
  219. }
  220. private void DoWriteLine(string message)
  221. {
  222. int indent = GetIndent();
  223. string s =
  224. string.Format(CultureInfo.InvariantCulture, "[{0:yyyy-MM-dd HH:mm:ss.fffZ}] [{1:x4}] {2}{3}",
  225. DateTime.Now, Thread.CurrentThread.ManagedThreadId,
  226. (indent > 0 ? new string(' ', indent * 2) : string.Empty), message);
  227. _writter.WriteLine(s);
  228. }
  229. private void SetLogPath(string value)
  230. {
  231. lock (_logLock)
  232. {
  233. if (_logPath != value)
  234. {
  235. Dispose();
  236. _logPath = value;
  237. if (!string.IsNullOrEmpty(_logPath))
  238. {
  239. _writter = File.CreateText(_logPath);
  240. _writter.AutoFlush = true;
  241. WriteEnvironmentInfo();
  242. CreateCounters();
  243. }
  244. }
  245. }
  246. }
  247. private void WriteEnvironmentInfo()
  248. {
  249. string path = GetAssemblyFilePath();
  250. FileVersionInfo version = string.IsNullOrEmpty(path) ? null : FileVersionInfo.GetVersionInfo(path);
  251. Assembly assembly = Assembly.GetExecutingAssembly();
  252. WriteLine("Executing Assembly: {0}; Path: {1}; Location: {2}; Product: {3}", assembly, path, assembly.Location, ((version != null) ? version.ProductVersion : "unknown"));
  253. WriteLine("Entry Assembly: {0}", Assembly.GetEntryAssembly());
  254. WriteLine("Operating system: {0}", Environment.OSVersion);
  255. WriteLine("User: {0}@{1}@{2}; Interactive: {3}", Environment.UserName, Environment.UserDomainName, Environment.MachineName, Environment.UserInteractive);
  256. WriteLine("Runtime: {0}", Environment.Version);
  257. WriteLine("Console encoding: Input: {0} ({1}); Output: {2} ({3})", Console.InputEncoding.EncodingName, Console.InputEncoding.CodePage, Console.OutputEncoding.EncodingName, Console.OutputEncoding.CodePage);
  258. WriteLine("Working directory: {0}", Environment.CurrentDirectory);
  259. }
  260. public static string LastWin32ErrorMessage()
  261. {
  262. return new Win32Exception(Marshal.GetLastWin32Error()).Message;
  263. }
  264. private StreamWriter _writter;
  265. private string _logPath;
  266. private readonly Dictionary<int, int> _indents = new Dictionary<int, int>();
  267. private readonly object _logLock = new object();
  268. private readonly Lock _lock = new Lock();
  269. private List<PerformanceCounter> _performanceCounters = new List<PerformanceCounter>();
  270. }
  271. }