CollectDataLog.cs 2.3 KB

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