Log.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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("../Log"))
  21. {
  22. Directory.CreateDirectory("../Log");
  23. }
  24. string s = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
  25. info = new StreamWriter($"../Log/log-{s}.info.log", false, Encoding.Unicode, 1024);
  26. error = new StreamWriter($"../Log/log-{s}.error.log", false, Encoding.Unicode, 1024);
  27. }
  28. public static void Warning(string msg)
  29. {
  30. DateTime dateTime = DateTime.Now;
  31. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {msg}";
  32. info.WriteLine(s);
  33. if (IsNeedFlush)
  34. {
  35. info.Flush();
  36. }
  37. #if UNITY_EDITOR
  38. UnityEngine.Debug.LogWarning(s);
  39. #endif
  40. }
  41. public static void Info(string msg)
  42. {
  43. DateTime dateTime = DateTime.Now;
  44. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {msg}";
  45. info.WriteLine(s);
  46. if (IsNeedFlush)
  47. {
  48. info.Flush();
  49. }
  50. #if UNITY_EDITOR
  51. UnityEngine.Debug.Log(s);
  52. #endif
  53. }
  54. public static void Error(string msg)
  55. {
  56. DateTime dateTime = DateTime.Now;
  57. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {TimeHelper.ClientNow()} {msg}";
  58. error.WriteLine(s);
  59. if (IsNeedFlush)
  60. {
  61. error.Flush();
  62. }
  63. #if UNITY_EDITOR
  64. UnityEngine.Debug.LogError(s);
  65. #endif
  66. long timeNow = TimeHelper.ClientNow();
  67. if (timeNow - SendToServerTime > SendToServerFrequency)
  68. {
  69. SendToServerTime = timeNow;
  70. }
  71. }
  72. public static void Debug(string msg)
  73. {
  74. #if UNITY_EDITOR
  75. DateTime dateTime = DateTime.Now;
  76. string s = $"{dateTime.ToString("yyyy-MM-dd HH:mm:ss")} {TimeHelper.ClientNow()} {msg}";
  77. UnityEngine.Debug.Log(s);
  78. #endif
  79. }
  80. public static void Flush()
  81. {
  82. info.Flush();
  83. error.Flush();
  84. }
  85. }
  86. }