Logger.cs 9.5 KB

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