Logger.cs 10 KB

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