You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Logging.cs 2.8 kB

10 years ago
10 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. namespace Shadowsocks.Controller
  7. {
  8. public class Logging
  9. {
  10. public static string LogFile;
  11. public static bool OpenLogFile()
  12. {
  13. try
  14. {
  15. string temppath = Path.GetTempPath();
  16. LogFile = Path.Combine(temppath, "shadowsocks.log");
  17. FileStream fs = new FileStream(LogFile, FileMode.Append);
  18. StreamWriterWithTimestamp sw = new StreamWriterWithTimestamp(fs);
  19. sw.AutoFlush = true;
  20. Console.SetOut(sw);
  21. Console.SetError(sw);
  22. return true;
  23. }
  24. catch (IOException e)
  25. {
  26. Console.WriteLine(e.ToString());
  27. return false;
  28. }
  29. }
  30. public static void Debug(object o)
  31. {
  32. #if DEBUG
  33. Console.WriteLine(o);
  34. #endif
  35. }
  36. public static void LogUsefulException(Exception e)
  37. {
  38. // just log useful exceptions, not all of them
  39. if (e is SocketException)
  40. {
  41. SocketException se = (SocketException)e;
  42. if (se.SocketErrorCode == SocketError.ConnectionAborted)
  43. {
  44. // closed by browser when sending
  45. // normally happens when download is canceled or a tab is closed before page is loaded
  46. }
  47. else if (se.SocketErrorCode == SocketError.ConnectionReset)
  48. {
  49. // received rst
  50. }
  51. else if (se.SocketErrorCode == SocketError.NotConnected)
  52. {
  53. // close when not connected
  54. }
  55. else
  56. {
  57. Console.WriteLine(e);
  58. }
  59. }
  60. else
  61. {
  62. Console.WriteLine(e);
  63. }
  64. }
  65. }
  66. // Simply extended System.IO.StreamWriter for adding timestamp workaround
  67. public class StreamWriterWithTimestamp : StreamWriter
  68. {
  69. public StreamWriterWithTimestamp(Stream stream) : base(stream)
  70. {
  71. }
  72. private string GetTimestamp()
  73. {
  74. return "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ";
  75. }
  76. public override void WriteLine(string value)
  77. {
  78. base.WriteLine(GetTimestamp() + value);
  79. }
  80. public override void Write(string value)
  81. {
  82. base.Write(GetTimestamp() + value);
  83. }
  84. }
  85. }