12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApp1.Else
- {
- public static class EvHttpClientLoggerTest
- {
- public static async Task Test()
- {
- int file_cnt = 0;
- while (true)
- {
- EvHttpClientLogger.Instance.StartNewLog(file_cnt.ToString());
- for (int i = 0; i < 10; i++)
- {
- EvHttpClientLogger.Instance.Log(i.ToString());
- await Task.Delay(1000);
- }
- file_cnt++;
- }
- }
- }
- public class EvHttpClientLogger
- {
- public static EvHttpClientLogger Instance => _Instance;
- private static EvHttpClientLogger _Instance = new EvHttpClientLogger();
- private EvHttpClientLogger()
- {
- if (!Directory.Exists(FolderName))
- {
- Directory.CreateDirectory(FolderName);
- }
- }
- private const string FolderName = "ApiLog";
- private const int MaxLogCnt = 10;
- private string LogFileName = null;
- internal void StartNewLog(string name)
- {
- TryRemoveOneLog();
- LogFileName = name + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".txt";
- }
- internal void Log(string mesasage)
- {
- if (string.IsNullOrEmpty(LogFileName))
- {
- return;
- }
- File.AppendAllText(Path.Combine(FolderName, LogFileName), mesasage + Environment.NewLine);
- }
- private void TryRemoveOneLog()
- {
- var files = Directory.GetFiles(FolderName).ToList();
- if (files.Count < MaxLogCnt)
- {
- return;
- }
- List<FileInfo> fileInfos = new List<FileInfo>();
- foreach (var file in files)
- {
- fileInfos.Add(new FileInfo(file));
- }
- var candidateFile = fileInfos.OrderBy(x => x.LastWriteTimeUtc).First();
- candidateFile.Delete();
- }
- }
- }
|