Log.cs 3.2 KB

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