1
0

Logger.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. _processorCounters.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. }
  135. }
  136. public void WriteCounters()
  137. {
  138. if (Logging)
  139. {
  140. try
  141. {
  142. foreach (PerformanceCounter counter in _processorCounters)
  143. {
  144. WriteLine("{0}{1}{2} = [{3}]",
  145. counter.CounterName,
  146. (string.IsNullOrEmpty(counter.InstanceName) ? string.Empty : "/"),
  147. counter.InstanceName,
  148. counter.NextValue());
  149. }
  150. }
  151. catch (Exception e)
  152. {
  153. WriteLine("Error reading counters: {0}", e);
  154. }
  155. }
  156. }
  157. public void WriteProcesses()
  158. {
  159. if (Logging)
  160. {
  161. try
  162. {
  163. Process[] processes = Process.GetProcesses();
  164. foreach (Process process in processes)
  165. {
  166. WriteLine("{0}:{1} - {2} - {3}", process.Id, process.ProcessName, GetProcessStartTime(process), GetTotalProcessorTime(process));
  167. }
  168. }
  169. catch (Exception e)
  170. {
  171. WriteLine("Error logging processes: {0}", e);
  172. }
  173. }
  174. }
  175. private static object GetProcessStartTime(Process process)
  176. {
  177. try
  178. {
  179. return process.StartTime;
  180. }
  181. catch
  182. {
  183. return "???";
  184. }
  185. }
  186. private static object GetTotalProcessorTime(Process process)
  187. {
  188. try
  189. {
  190. return process.TotalProcessorTime;
  191. }
  192. catch
  193. {
  194. return "???";
  195. }
  196. }
  197. public Callstack CreateCallstack()
  198. {
  199. return new Callstack(this);
  200. }
  201. public Callstack CreateCallstackAndLock()
  202. {
  203. return new CallstackAndLock(this, _lock);
  204. }
  205. private int GetIndent()
  206. {
  207. int indent;
  208. if (!_indents.TryGetValue(GetThread(), out indent))
  209. {
  210. indent = 0;
  211. }
  212. return indent;
  213. }
  214. private void DoWriteLine(string message)
  215. {
  216. int indent = GetIndent();
  217. string s =
  218. string.Format(CultureInfo.InvariantCulture, "[{0:yyyy-MM-dd HH:mm:ss.fffZ}] [{1:x4}] {2}{3}",
  219. DateTime.Now, Thread.CurrentThread.ManagedThreadId,
  220. (indent > 0 ? new string(' ', indent * 2) : string.Empty), message);
  221. _writter.WriteLine(s);
  222. }
  223. private void SetLogPath(string value)
  224. {
  225. lock (_logLock)
  226. {
  227. if (_logPath != value)
  228. {
  229. Dispose();
  230. _logPath = value;
  231. if (!string.IsNullOrEmpty(_logPath))
  232. {
  233. _writter = File.CreateText(_logPath);
  234. _writter.AutoFlush = true;
  235. WriteEnvironmentInfo();
  236. CreateCounters();
  237. }
  238. }
  239. }
  240. }
  241. private void WriteEnvironmentInfo()
  242. {
  243. string path = GetAssemblyFilePath();
  244. FileVersionInfo version = string.IsNullOrEmpty(path) ? null : FileVersionInfo.GetVersionInfo(path);
  245. Assembly assembly = Assembly.GetExecutingAssembly();
  246. WriteLine("Executing Assembly: {0}; Path: {1}; Location: {2}; Product: {3}", assembly, path, assembly.Location, ((version != null) ? version.ProductVersion : "unknown"));
  247. WriteLine("Entry Assembly: {0}", Assembly.GetEntryAssembly());
  248. WriteLine("Operating system: {0}", Environment.OSVersion);
  249. WriteLine("User: {0}@{1}@{2}; Interactive: {3}", Environment.UserName, Environment.UserDomainName, Environment.MachineName, Environment.UserInteractive);
  250. WriteLine("Runtime: {0}", Environment.Version);
  251. WriteLine("Console encoding: Input: {0} ({1}); Output: {2} ({3})", Console.InputEncoding.EncodingName, Console.InputEncoding.CodePage, Console.OutputEncoding.EncodingName, Console.OutputEncoding.CodePage);
  252. WriteLine("Working directory: {0}", Environment.CurrentDirectory);
  253. }
  254. private StreamWriter _writter;
  255. private string _logPath;
  256. private readonly Dictionary<int, int> _indents = new Dictionary<int, int>();
  257. private readonly object _logLock = new object();
  258. private readonly Lock _lock = new Lock();
  259. private List<PerformanceCounter> _processorCounters = new List<PerformanceCounter>();
  260. }
  261. }