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

10 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 LogUsefulException(Exception e)
  31. {
  32. // just log useful exceptions, not all of them
  33. if (e is SocketException)
  34. {
  35. SocketException se = (SocketException)e;
  36. if (se.SocketErrorCode == SocketError.ConnectionAborted)
  37. {
  38. // closed by browser when sending
  39. // normally happens when download is canceled or a tab is closed before page is loaded
  40. }
  41. else if (se.SocketErrorCode == SocketError.ConnectionReset)
  42. {
  43. // received rst
  44. }
  45. else if (se.SocketErrorCode == SocketError.NotConnected)
  46. {
  47. // close when not connected
  48. }
  49. else
  50. {
  51. Console.WriteLine(e);
  52. }
  53. }
  54. else
  55. {
  56. Console.WriteLine(e);
  57. }
  58. }
  59. }
  60. // Simply extended System.IO.StreamWriter for adding timestamp workaround
  61. public class StreamWriterWithTimestamp : StreamWriter
  62. {
  63. public StreamWriterWithTimestamp(Stream stream) : base(stream)
  64. {
  65. }
  66. private string GetTimestamp()
  67. {
  68. return "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ";
  69. }
  70. public override void WriteLine(string value)
  71. {
  72. base.WriteLine(GetTimestamp() + value);
  73. }
  74. public override void Write(string value)
  75. {
  76. base.Write(GetTimestamp() + value);
  77. }
  78. }
  79. }