You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.9 KiB
C#

using Ems.CollectService.Common;
using NLog;
using System;
using System.IO;
using Ems.CollectService.Entity.config;
namespace Ems.CollectService.Timer
{
/// <summary>
/// 删除日志文件
/// </summary>
public sealed class DeleteLogFile
{
private Logger logger = LogManager.GetCurrentClassLogger();
//private System.Timers.Timer timer = new System.Timers.Timer(1000*60*60);
private AppConfig _appConfig = AppConfig.Instance;
private static readonly Lazy<DeleteLogFile> lazy = new Lazy<DeleteLogFile>(() => new DeleteLogFile());
public static DeleteLogFile Instance
{
get
{
return lazy.Value;
}
}
private DeleteLogFile() { }
/// <summary>
/// 删除日志定时器
/// </summary>
public void DeleteLogFileTimer()
{
System.Timers.Timer timer = new System.Timers.Timer(_appConfig.deleteLogTimer);
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}");
}
}
/// <summary>
/// 删除指定路径下的超时文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DeleteLogFileTick(object sender, EventArgs e)
{
try
{
string fileDirect = _appConfig.logFilePath;
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}");
}
}
}
}