Log.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. Console.WriteLine("进入消息执行方法体:" + msg + "路径==》" + path);
  34. if (string.IsNullOrEmpty(path))
  35. {
  36. path = DateTime.Now.ToString("yyyy-MM-dd");
  37. }
  38. else
  39. {
  40. path = path + " " + DateTime.Now.ToString("yyyy-MM-dd");
  41. }
  42. streamWriter = new System.IO.StreamWriter(Path + "\\" + path + ".txt", true);
  43. streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg);
  44. streamWriter.Close();
  45. this.EveShowLog?.Invoke(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg);
  46. Console.WriteLine("完成日志写入");
  47. }catch(Exception e)
  48. {
  49. Console.WriteLine("写入日志异常");
  50. }
  51. }
  52. private void ThreadWrite()
  53. {
  54. Task.Factory.StartNew(() =>
  55. {
  56. while (true)
  57. {
  58. System.Threading.Thread.Sleep(20);
  59. if (qs.Count > 0)
  60. {
  61. if (qs.TryDequeue(out item))
  62. {
  63. WriteLog(item.msg, item.path);
  64. }
  65. }
  66. }
  67. });
  68. }
  69. }
  70. public class LogDefaultList
  71. {
  72. public string path { get; set; }
  73. public string msg { get; set; }
  74. }
  75. }