Logger.cs 11 KB

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