Log.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. namespace WCS
  6. {
  7. public class Log
  8. {
  9. private static Log _log = new Log();
  10. public static Log Instance { get { return _log; } }
  11. LogDefaultList item = new LogDefaultList();
  12. string Path = AppDomain.CurrentDomain.BaseDirectory + "webApiLog";
  13. ConcurrentQueue<LogDefaultList> qs = new ConcurrentQueue<LogDefaultList>();
  14. System.IO.StreamWriter streamWriter;
  15. public Log()
  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 LogDefaultList() { 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 LogDefaultList
  63. {
  64. public string path { get; set; }
  65. public string msg { get; set; }
  66. }
  67. }