LogBase.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. *
  27. */
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Diagnostics;
  31. using System.IO;
  32. using System.Net;
  33. namespace OpenSim.Framework.Console
  34. {
  35. public enum LogPriority : int
  36. {
  37. CRITICAL,
  38. HIGH,
  39. MEDIUM,
  40. NORMAL,
  41. LOW,
  42. VERBOSE,
  43. EXTRAVERBOSE
  44. }
  45. public class LogBase
  46. {
  47. private object m_syncRoot = new object();
  48. private StreamWriter Log;
  49. public conscmd_callback cmdparser;
  50. public string componentname;
  51. private bool m_verbose;
  52. public LogBase(string LogFile, string componentname, conscmd_callback cmdparser, bool verbose)
  53. {
  54. this.componentname = componentname;
  55. this.cmdparser = cmdparser;
  56. m_verbose = verbose;
  57. System.Console.WriteLine("Creating new local console");
  58. if (String.IsNullOrEmpty(LogFile))
  59. {
  60. LogFile = componentname + ".log";
  61. }
  62. System.Console.WriteLine("Logs will be saved to current directory in " + LogFile);
  63. Log = File.AppendText(LogFile);
  64. Log.WriteLine("========================================================================");
  65. Log.WriteLine(componentname + " Started at " + DateTime.Now.ToString());
  66. }
  67. public void Close()
  68. {
  69. Log.WriteLine("Shutdown at " + DateTime.Now.ToString());
  70. Log.Close();
  71. }
  72. /// <summary>
  73. /// derive an ansi color from a string, ignoring the darker colors.
  74. /// This is used to help automatically bin component tags with colors
  75. /// in various print functions.
  76. /// </summary>
  77. /// <param name="input">arbitrary string for input</param>
  78. /// <returns>an ansii color</returns>
  79. private ConsoleColor DeriveColor(string input)
  80. {
  81. int colIdx = (input.ToUpper().GetHashCode()%6) + 9;
  82. return (ConsoleColor) colIdx;
  83. }
  84. /// <summary>
  85. /// Sends a warning to the current log output
  86. /// </summary>
  87. /// <param name="format">The message to send</param>
  88. /// <param name="args">WriteLine-style message arguments</param>
  89. public void Warn(string format, params object[] args)
  90. {
  91. WriteNewLine(ConsoleColor.Yellow, format, args);
  92. return;
  93. }
  94. /// <summary>
  95. /// Sends a warning to the current log output
  96. /// </summary>
  97. /// <param name="sender">The module that sent this message</param>
  98. /// <param name="format">The message to send</param>
  99. /// <param name="args">WriteLine-style message arguments</param>
  100. public void Warn(string sender, string format, params object[] args)
  101. {
  102. WritePrefixLine(DeriveColor(sender), sender);
  103. WriteNewLine(ConsoleColor.Yellow, format, args);
  104. return;
  105. }
  106. /// <summary>
  107. /// Sends a notice to the current log output
  108. /// </summary>
  109. /// <param name="format">The message to send</param>
  110. /// <param name="args">WriteLine-style message arguments</param>
  111. public void Notice(string format, params object[] args)
  112. {
  113. WriteNewLine(ConsoleColor.White, format, args);
  114. return;
  115. }
  116. /// <summary>
  117. /// Sends a notice to the current log output
  118. /// </summary>
  119. /// <param name="sender">The module that sent this message</param>
  120. /// <param name="format">The message to send</param>
  121. /// <param name="args">WriteLine-style message arguments</param>
  122. public void Notice(string sender, string format, params object[] args)
  123. {
  124. WritePrefixLine(DeriveColor(sender), sender);
  125. WriteNewLine(ConsoleColor.White, format, args);
  126. return;
  127. }
  128. /// <summary>
  129. /// Sends an error to the current log output
  130. /// </summary>
  131. /// <param name="format">The message to send</param>
  132. /// <param name="args">WriteLine-style message arguments</param>
  133. public void Error(string format, params object[] args)
  134. {
  135. WriteNewLine(ConsoleColor.Red, format, args);
  136. return;
  137. }
  138. /// <summary>
  139. /// Sends an error to the current log output
  140. /// </summary>
  141. /// <param name="sender">The module that sent this message</param>
  142. /// <param name="format">The message to send</param>
  143. /// <param name="args">WriteLine-style message arguments</param>
  144. public void Error(string sender, string format, params object[] args)
  145. {
  146. WritePrefixLine(DeriveColor(sender), sender);
  147. Error(format, args);
  148. return;
  149. }
  150. /// <summary>
  151. /// Sends an informational message to the current log output
  152. /// </summary>
  153. /// <param name="sender">The module that sent this message</param>
  154. /// <param name="format">The message to send</param>
  155. /// <param name="args">WriteLine-style message arguments</param>
  156. public void Verbose(string sender, string format, params object[] args)
  157. {
  158. if (m_verbose)
  159. {
  160. WritePrefixLine(DeriveColor(sender), sender);
  161. WriteNewLine(ConsoleColor.Gray, format, args);
  162. return;
  163. }
  164. }
  165. /// <summary>
  166. /// Sends a status message to the current log output
  167. /// </summary>
  168. /// <param name="format">The message to send</param>
  169. /// <param name="args">WriteLine-style message arguments</param>
  170. public void Status(string format, params object[] args)
  171. {
  172. WriteNewLine(ConsoleColor.Blue, format, args);
  173. return;
  174. }
  175. /// <summary>
  176. /// Sends a status message to the current log output
  177. /// </summary>
  178. /// <param name="sender">The module that sent this message</param>
  179. /// <param name="format">The message to send</param>
  180. /// <param name="args">WriteLine-style message arguments</param>
  181. public void Status(string sender, string format, params object[] args)
  182. {
  183. WritePrefixLine(DeriveColor(sender), sender);
  184. WriteNewLine(ConsoleColor.Blue, format, args);
  185. return;
  186. }
  187. [Conditional("DEBUG")]
  188. public void Debug(string format, params object[] args)
  189. {
  190. WriteNewLine(ConsoleColor.Gray, format, args);
  191. return;
  192. }
  193. [Conditional("DEBUG")]
  194. public void Debug(string sender, string format, params object[] args)
  195. {
  196. WritePrefixLine(DeriveColor(sender), sender);
  197. WriteNewLine(ConsoleColor.Gray, format, args);
  198. return;
  199. }
  200. private void WriteNewLine(ConsoleColor color, string format, params object[] args)
  201. {
  202. lock (m_syncRoot)
  203. {
  204. string now = DateTime.Now.ToString("[MM-dd hh:mm:ss] ");
  205. Log.Write(now);
  206. try
  207. {
  208. Log.WriteLine(format, args);
  209. Log.Flush();
  210. }
  211. catch (FormatException)
  212. {
  213. System.Console.WriteLine(args);
  214. }
  215. System.Console.Write(now);
  216. try
  217. {
  218. if (color != ConsoleColor.White)
  219. System.Console.ForegroundColor = color;
  220. System.Console.WriteLine(format, args);
  221. System.Console.ResetColor();
  222. }
  223. catch (ArgumentNullException)
  224. {
  225. // Some older systems dont support coloured text.
  226. System.Console.WriteLine(format, args);
  227. }
  228. catch (FormatException)
  229. {
  230. // Some older systems dont support coloured text.
  231. System.Console.WriteLine(args);
  232. }
  233. return;
  234. }
  235. }
  236. private void WritePrefixLine(ConsoleColor color, string sender)
  237. {
  238. lock (m_syncRoot)
  239. {
  240. sender = sender.ToUpper();
  241. Log.WriteLine("[" + sender + "] ");
  242. Log.Flush();
  243. System.Console.Write("[");
  244. try
  245. {
  246. System.Console.ForegroundColor = color;
  247. System.Console.Write(sender);
  248. System.Console.ResetColor();
  249. }
  250. catch (ArgumentNullException)
  251. {
  252. // Some older systems dont support coloured text.
  253. System.Console.WriteLine(sender);
  254. }
  255. System.Console.Write("] \t");
  256. return;
  257. }
  258. }
  259. public string ReadLine()
  260. {
  261. try
  262. {
  263. string TempStr = System.Console.ReadLine();
  264. Log.WriteLine(TempStr);
  265. return TempStr;
  266. }
  267. catch (Exception e)
  268. {
  269. MainLog.Instance.Error("Console", "System.Console.ReadLine exception " + e.ToString());
  270. return "";
  271. }
  272. }
  273. public int Read()
  274. {
  275. int TempInt = System.Console.Read();
  276. Log.Write((char) TempInt);
  277. return TempInt;
  278. }
  279. public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue)
  280. {
  281. IPAddress address;
  282. string addressStr;
  283. while (true)
  284. {
  285. addressStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue);
  286. if (IPAddress.TryParse(addressStr, out address))
  287. {
  288. break;
  289. }
  290. else
  291. {
  292. MainLog.Instance.Error("Illegal address. Please re-enter.");
  293. }
  294. }
  295. return address;
  296. }
  297. public uint CmdPromptIPPort(string prompt, string defaultvalue)
  298. {
  299. uint port;
  300. string portStr;
  301. while (true)
  302. {
  303. portStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue);
  304. if (uint.TryParse(portStr, out port))
  305. {
  306. if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort)
  307. {
  308. break;
  309. }
  310. }
  311. MainLog.Instance.Error("Illegal address. Please re-enter.");
  312. }
  313. return port;
  314. }
  315. // Displays a prompt and waits for the user to enter a string, then returns that string
  316. // Done with no echo and suitable for passwords
  317. public string PasswdPrompt(string prompt)
  318. {
  319. // FIXME: Needs to be better abstracted
  320. Log.WriteLine(prompt);
  321. Notice(prompt);
  322. ConsoleColor oldfg = System.Console.ForegroundColor;
  323. System.Console.ForegroundColor = System.Console.BackgroundColor;
  324. string temp = System.Console.ReadLine();
  325. System.Console.ForegroundColor = oldfg;
  326. return temp;
  327. }
  328. // Displays a command prompt and waits for the user to enter a string, then returns that string
  329. public string CmdPrompt(string prompt)
  330. {
  331. Notice(String.Format("{0}: ", prompt));
  332. return ReadLine();
  333. }
  334. // Displays a command prompt and returns a default value if the user simply presses enter
  335. public string CmdPrompt(string prompt, string defaultresponse)
  336. {
  337. string temp = CmdPrompt(String.Format("{0} [{1}]", prompt, defaultresponse));
  338. if (temp == "")
  339. {
  340. return defaultresponse;
  341. }
  342. else
  343. {
  344. return temp;
  345. }
  346. }
  347. // Displays a command prompt and returns a default value, user may only enter 1 of 2 options
  348. public string CmdPrompt(string prompt, string defaultresponse, string OptionA, string OptionB)
  349. {
  350. bool itisdone = false;
  351. string temp = CmdPrompt(prompt, defaultresponse);
  352. while (itisdone == false)
  353. {
  354. if ((temp == OptionA) || (temp == OptionB))
  355. {
  356. itisdone = true;
  357. }
  358. else
  359. {
  360. Notice("Valid options are " + OptionA + " or " + OptionB);
  361. temp = CmdPrompt(prompt, defaultresponse);
  362. }
  363. }
  364. return temp;
  365. }
  366. // Runs a command with a number of parameters
  367. public Object RunCmd(string Cmd, string[] cmdparams)
  368. {
  369. cmdparser.RunCmd(Cmd, cmdparams);
  370. return null;
  371. }
  372. // Shows data about something
  373. public void ShowCommands(string ShowWhat)
  374. {
  375. cmdparser.Show(ShowWhat);
  376. }
  377. public void MainLogPrompt()
  378. {
  379. string tempstr = CmdPrompt(componentname + "# ");
  380. MainLogRunCommand(tempstr);
  381. }
  382. public void MainLogRunCommand(string command)
  383. {
  384. string[] tempstrarray;
  385. tempstrarray = command.Split(' ');
  386. string cmd = tempstrarray[0];
  387. Array.Reverse(tempstrarray);
  388. Array.Resize<string>(ref tempstrarray, tempstrarray.Length - 1);
  389. Array.Reverse(tempstrarray);
  390. string[] cmdparams = (string[]) tempstrarray;
  391. try
  392. {
  393. RunCmd(cmd, cmdparams);
  394. }
  395. catch (Exception e)
  396. {
  397. MainLog.Instance.Error("Console", "Command failed with exception " + e.ToString());
  398. }
  399. }
  400. public string LineInfo
  401. {
  402. get
  403. {
  404. string result = String.Empty;
  405. string stacktrace = Environment.StackTrace;
  406. List<string> lines = new List<string>(stacktrace.Split(new string[] {"at "}, StringSplitOptions.None));
  407. if (lines.Count > 4)
  408. {
  409. lines.RemoveRange(0, 4);
  410. string tmpLine = lines[0];
  411. int inIndex = tmpLine.IndexOf(" in ");
  412. if (inIndex > -1)
  413. {
  414. result = tmpLine.Substring(0, inIndex);
  415. int lineIndex = tmpLine.IndexOf(":line ");
  416. if (lineIndex > -1)
  417. {
  418. lineIndex += 6;
  419. result += ", line " + tmpLine.Substring(lineIndex, (tmpLine.Length - lineIndex) - 5);
  420. }
  421. }
  422. }
  423. return result;
  424. }
  425. }
  426. }
  427. }