using Ems.CollectService.Common;
using NLog;
using System;
using System.IO;
namespace Ems.CollectService.Timer
{
///
/// 删除日志文件
///
public sealed class DeleteLogFile
{
private Logger logger = LogManager.GetCurrentClassLogger();
private System.Timers.Timer timer = new System.Timers.Timer(1000*60*60);
private static readonly Lazy lazy = new Lazy(() => new DeleteLogFile());
public static DeleteLogFile Instance
{
get
{
return lazy.Value;
}
}
private DeleteLogFile() { }
///
/// 删除日志定时器
///
public void DeleteLogFileTimer()
{
try
{
if (!timer.Enabled)
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(DeleteLogFileTick);
timer.AutoReset = true;
timer.Enabled = false;
timer.Start();
logger.Info("删除日志文件夹定时器启动成功");
}
}
catch (Exception ex)
{
logger.Error($"StartTimerDeleteLogFile定时删除日志文件异常{ex.Message}");
}
}
///
/// 删除指定路径下的超时文件
///
///
///
private void DeleteLogFileTick(object sender, EventArgs e)
{
try
{
string fileDirect = "C:\\能源项目文件夹\\采集服务\\Log";
int saveDay = 1;
logger.Info($"定时删除路径:{fileDirect};下超过:{saveDay}天的日志文件夹");
DateTime nowTime = DateTime.Now;
DirectoryInfo root = new DirectoryInfo(fileDirect);
DirectoryInfo[] dics = root.GetDirectories();
FileAttributes attr = File.GetAttributes(fileDirect);
if (attr == FileAttributes.Directory)
{
foreach (DirectoryInfo file in dics)
{
TimeSpan t = nowTime - file.CreationTime;
int day = t.Days;
if (day > saveDay)
{
Directory.Delete(file.FullName, true);
}
}
}
}
catch (Exception ex)
{
logger.Error($"删除日志文件夹异常{ex.Message}");
}
}
}
}