Log.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using DaJiaoYan.Variables;
  2. using System;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. namespace DaJiaoYan.Utils
  6. {
  7. internal class Log
  8. {
  9. private readonly static object _lock = new object();
  10. /// <summary>
  11. /// 当前全部日志
  12. /// </summary>
  13. private static string LogAll = "";
  14. /// <summary>
  15. /// 临时日志
  16. /// </summary>
  17. private static string LogTmp = "";
  18. /// <summary>
  19. /// 日志处理的委托
  20. /// </summary>
  21. /// <param name="s"></param>
  22. public delegate void SetLog(string s);
  23. /// <summary>
  24. /// 具体委托的实例
  25. /// </summary>
  26. //public static SetLog DoSetLog;
  27. public static string Now()
  28. {
  29. return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  30. }
  31. private static string Today()
  32. {
  33. return DateTime.Now.ToString("yyyy-MM-dd");
  34. }
  35. /// <summary>
  36. /// 记录错误
  37. /// </summary>
  38. /// <param name="exception"></param>
  39. public static void Error(Exception exception)
  40. {
  41. WriteLine(exception.StackTrace, "error", force: true);
  42. }
  43. /// <summary>
  44. /// 记录信息
  45. /// </summary>
  46. /// <param name="s"></param>
  47. /// <param name="t"></param>
  48. /// <param name="filename"></param>
  49. public static void WriteLine(string s, string t = "log", string filename = null, bool force = false)
  50. {
  51. if (s != null)
  52. {
  53. string info = $"{Now()} [{t}] {s}\r\n";
  54. Console.Write(info);
  55. lock (_lock)
  56. {
  57. LogAll = string.Concat(LogAll, info);
  58. LogTmp = string.Concat(LogTmp, info);
  59. }
  60. //#if DEBUG
  61. // DoSetLog?.Invoke(Variables.Variables.LogTmp);
  62. //#endif
  63. Save(force);
  64. }
  65. }
  66. /// <summary>
  67. /// 保存信息
  68. /// </summary>
  69. /// <param name="force"></param>
  70. public static void Save(bool force = false, string filename = null)
  71. {
  72. if (force || LogTmp.Length > 30000)
  73. {
  74. if (string.IsNullOrEmpty(filename))
  75. {
  76. filename = Today();
  77. }
  78. string txt;
  79. lock (_lock)
  80. {
  81. txt = LogTmp;
  82. LogTmp = "";
  83. }
  84. Task.Run(() =>
  85. {
  86. FileExts.AppendAllText(Path.Combine(Const.LOG_DIR, $"{filename}.txt"), txt);
  87. });
  88. }
  89. }
  90. }
  91. }