using FluentScheduler;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;

namespace Performance.Api
{
    /// <summary>
    /// 删除历史日志
    /// </summary>
    public class ClearLoggerJob : IJob
    {
        private readonly ILogger<ClearLoggerJob> _logger;

        public ClearLoggerJob(ILogger<ClearLoggerJob> logger)
        {
            _logger = logger;
        }

        public void Execute()
        {
            try
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
                if (!Directory.Exists(path)) return;

                var directories = Directory.GetDirectories(path);

                foreach (var d in directories)
                {
                    DirectoryInfo info = new DirectoryInfo(d);
                    if (info.LastWriteTime < DateTime.Now.AddMonths(-3))
                        Directory.Delete(d, true);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("删除日志异常：{ex}", ex);
            }
        }
    }
}
