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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 if (e is ObjectDisposedException)
  61. {
  62. }
  63. else
  64. {
  65. Console.WriteLine(e);
  66. }
  67. }
  68. }
  69. // Simply extended System.IO.StreamWriter for adding timestamp workaround
  70. public class StreamWriterWithTimestamp : StreamWriter
  71. {
  72. public StreamWriterWithTimestamp(Stream stream) : base(stream)
  73. {
  74. }
  75. private string GetTimestamp()
  76. {
  77. return "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ";
  78. }
  79. public override void WriteLine(string value)
  80. {
  81. base.WriteLine(GetTimestamp() + value);
  82. }
  83. public override void Write(string value)
  84. {
  85. base.Write(GetTimestamp() + value);
  86. }
  87. }
  88. }