Log.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace Base
  5. {
  6. public static class Log
  7. {
  8. private static StreamWriter info;
  9. private static StreamWriter error;
  10. // 每多少秒发一次
  11. public static long SendToServerFrequency = 20 * 1000;
  12. public static long SendToServerTime;
  13. #if UNITY_EDITOR
  14. private static bool IsNeedFlush = true;
  15. #else
  16. private static bool IsNeedFlush = false;
  17. #endif
  18. static Log()
  19. {
  20. if (!Directory.Exists("../Logs"))
  21. {
  22. Directory.CreateDirectory("../Logs");
  23. }
  24. info = new StreamWriter($"../Logs/Log-Client-Info.txt", false, Encoding.Unicode, 1024);
  25. error = new StreamWriter($"../Logs/Log-Client-Error.txt", false, Encoding.Unicode, 1024);
  26. }
  27. public static void Warning(string msg)
  28. {
  29. DateTime dateTime = DateTime.Now;
  30. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {msg}";
  31. info.WriteLine(s);
  32. if (IsNeedFlush)
  33. {
  34. info.Flush();
  35. }
  36. #if UNITY_EDITOR
  37. UnityEngine.Debug.LogWarning(s);
  38. #endif
  39. }
  40. public static void Info(string msg)
  41. {
  42. DateTime dateTime = DateTime.Now;
  43. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {msg}";
  44. info.WriteLine(s);
  45. if (IsNeedFlush)
  46. {
  47. info.Flush();
  48. }
  49. #if UNITY_EDITOR
  50. UnityEngine.Debug.Log(s);
  51. #endif
  52. }
  53. public static void Error(string msg)
  54. {
  55. DateTime dateTime = DateTime.Now;
  56. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {TimeHelper.ClientNow()} {msg}";
  57. error.WriteLine(s);
  58. if (IsNeedFlush)
  59. {
  60. error.Flush();
  61. }
  62. #if UNITY_EDITOR
  63. UnityEngine.Debug.LogError(s);
  64. #endif
  65. long timeNow = TimeHelper.ClientNow();
  66. if (timeNow - SendToServerTime > SendToServerFrequency)
  67. {
  68. SendToServerTime = timeNow;
  69. }
  70. }
  71. public static void Debug(string msg)
  72. {
  73. #if UNITY_EDITOR
  74. DateTime dateTime = DateTime.Now;
  75. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {TimeHelper.ClientNow()} {msg}";
  76. UnityEngine.Debug.Log(s);
  77. #endif
  78. }
  79. public static void Flush()
  80. {
  81. info.Flush();
  82. error.Flush();
  83. }
  84. }
  85. }