EvHttpClientLogger.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace AwInitilizer.Assist
  8. {
  9. public class EvHttpClientLogger
  10. {
  11. public static EvHttpClientLogger Instance => _Instance;
  12. private static EvHttpClientLogger _Instance = new EvHttpClientLogger();
  13. private EvHttpClientLogger()
  14. {
  15. if (!Directory.Exists(FolderName))
  16. {
  17. Directory.CreateDirectory(FolderName);
  18. }
  19. }
  20. private const string FolderName = "ApiLog";
  21. private const int MaxLogCnt = 10;
  22. private string LogFileName = null;
  23. internal void StartNewLog(string name)
  24. {
  25. TryRemoveOneLog();
  26. LogFileName = name + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".txt";
  27. }
  28. internal void Log(string mesasage)
  29. {
  30. if (string.IsNullOrEmpty(LogFileName))
  31. {
  32. return;
  33. }
  34. File.AppendAllText(Path.Combine(FolderName, LogFileName), mesasage + Environment.NewLine);
  35. }
  36. private void TryRemoveOneLog()
  37. {
  38. var files = Directory.GetFiles(FolderName).ToList();
  39. if (files.Count < MaxLogCnt)
  40. {
  41. return;
  42. }
  43. List<FileInfo> fileInfos = new List<FileInfo>();
  44. foreach (var file in files) {
  45. fileInfos.Add(new FileInfo(file));
  46. }
  47. var candidateFile = fileInfos.OrderBy(x => x.LastWriteTimeUtc).First();
  48. candidateFile.Delete();
  49. }
  50. }
  51. }