Log.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. namespace IMCS.CCS
  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. try
  32. {
  33. if (string.IsNullOrEmpty(path))
  34. {
  35. path = DateTime.Now.ToString("yyyy-MM-dd");
  36. }
  37. else
  38. {
  39. path = path + " " + DateTime.Now.ToString("yyyy-MM-dd");
  40. }
  41. streamWriter = new System.IO.StreamWriter(Path + "\\" + path + ".txt", true);
  42. streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg);
  43. streamWriter.Close();
  44. this.EveShowLog?.Invoke(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg);
  45. }catch(Exception ex)
  46. {
  47. Console.WriteLine("写入日志文件失败:" + ex.Message);
  48. streamWriter.Close();
  49. }
  50. }
  51. private void ThreadWrite()
  52. {
  53. Task.Factory.StartNew(() =>
  54. {
  55. while (true)
  56. {
  57. System.Threading.Thread.Sleep(20);
  58. if (qs.Count > 0)
  59. {
  60. if (qs.TryDequeue(out item))
  61. {
  62. WriteLog(item.msg, item.path);
  63. }
  64. }
  65. }
  66. });
  67. }
  68. }
  69. public class LogDefaultList
  70. {
  71. public string path { get; set; }
  72. public string msg { get; set; }
  73. }
  74. }