EvHttpClientLogger.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ConsoleApp1.Else
  7. {
  8. public static class EvHttpClientLoggerTest
  9. {
  10. public static async Task Test()
  11. {
  12. int file_cnt = 0;
  13. while (true)
  14. {
  15. EvHttpClientLogger.Instance.StartNewLog(file_cnt.ToString());
  16. for (int i = 0; i < 10; i++)
  17. {
  18. EvHttpClientLogger.Instance.Log(i.ToString());
  19. await Task.Delay(1000);
  20. }
  21. file_cnt++;
  22. }
  23. }
  24. }
  25. public class EvHttpClientLogger
  26. {
  27. public static EvHttpClientLogger Instance => _Instance;
  28. private static EvHttpClientLogger _Instance = new EvHttpClientLogger();
  29. private EvHttpClientLogger()
  30. {
  31. if (!Directory.Exists(FolderName))
  32. {
  33. Directory.CreateDirectory(FolderName);
  34. }
  35. }
  36. private const string FolderName = "ApiLog";
  37. private const int MaxLogCnt = 10;
  38. private string LogFileName = null;
  39. internal void StartNewLog(string name)
  40. {
  41. TryRemoveOneLog();
  42. LogFileName = name + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".txt";
  43. }
  44. internal void Log(string mesasage)
  45. {
  46. if (string.IsNullOrEmpty(LogFileName))
  47. {
  48. return;
  49. }
  50. File.AppendAllText(Path.Combine(FolderName, LogFileName), mesasage + Environment.NewLine);
  51. }
  52. private void TryRemoveOneLog()
  53. {
  54. var files = Directory.GetFiles(FolderName).ToList();
  55. if (files.Count < MaxLogCnt)
  56. {
  57. return;
  58. }
  59. List<FileInfo> fileInfos = new List<FileInfo>();
  60. foreach (var file in files)
  61. {
  62. fileInfos.Add(new FileInfo(file));
  63. }
  64. var candidateFile = fileInfos.OrderBy(x => x.LastWriteTimeUtc).First();
  65. candidateFile.Delete();
  66. }
  67. }
  68. }