Log.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace YG
  9. {
  10. public class Log
  11. {
  12. private static Log _log = new Log();
  13. public static Log Instance { get { return _log; } }
  14. LogDefaultList item = new LogDefaultList();
  15. string Path = AppDomain.CurrentDomain.BaseDirectory + "YGLog";
  16. ConcurrentQueue<LogDefaultList> qs = new ConcurrentQueue<LogDefaultList>();
  17. System.IO.StreamWriter streamWriter;
  18. public Log()
  19. {
  20. if (!System.IO.Directory.Exists(Path))
  21. {
  22. Directory.CreateDirectory(Path);
  23. }
  24. ThreadWrite();
  25. }
  26. public void WriteLogAdd(string msg, string path = null)
  27. {
  28. qs.Enqueue(new LogDefaultList() { msg = msg, path = path });
  29. }
  30. public delegate void DelShowLog(string msg);
  31. public event DelShowLog EveShowLog;
  32. private void WriteLog(string msg, string path)
  33. {
  34. if (string.IsNullOrEmpty(path))
  35. {
  36. path = DateTime.Now.ToString("yyyy-MM-dd");
  37. }
  38. streamWriter = new System.IO.StreamWriter(Path + "\\" + path + ".txt", true);
  39. streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg);
  40. streamWriter.Close();
  41. this.EveShowLog?.Invoke(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg);
  42. }
  43. private void ThreadWrite()
  44. {
  45. Task.Factory.StartNew(() =>
  46. {
  47. while (true)
  48. {
  49. System.Threading.Thread.Sleep(20);
  50. if (qs.Count > 0)
  51. {
  52. if (qs.TryDequeue(out item))
  53. {
  54. WriteLog(item.msg, item.path);
  55. }
  56. }
  57. }
  58. });
  59. }
  60. }
  61. public class LogDefaultList
  62. {
  63. public string path { get; set; }
  64. public string msg { get; set; }
  65. }
  66. }