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.9 kB

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