using Quartz;
|
using System;
|
using System.IO;
|
using System.Threading.Tasks;
|
using WIDESEA_Common.Log;
|
|
namespace WIDESEAWCS_Tasks
|
{
|
[DisallowConcurrentExecution]
|
public class LogJob : IJob
|
{
|
public Task Execute(IJobExecutionContext context)
|
{
|
try
|
{
|
Task.Run(() =>
|
{
|
try
|
{
|
WriteLog.GetLog("LogJob").Write($"日志记录:{DateTime.Now}", "LogJob");
|
|
// 设置保留天数为30天
|
int saveDays = 30;
|
|
// 清理Log目录下的所有过期文件夹
|
CleanLogDirectory(saveDays);
|
|
Thread.Sleep(1000 * 10);
|
}
|
catch (Exception ex)
|
{
|
WriteLog.GetLog("LogJob").Write($"日志清理出错:{ex.Message}", "LogJob");
|
}
|
});
|
}
|
catch (Exception ex)
|
{
|
Console.Out.WriteLine(nameof(LogJob) + ":" + ex.Message);
|
}
|
|
return Task.CompletedTask;
|
}
|
|
/// <summary>
|
/// 清理Log目录下的所有过期日志文件夹
|
/// </summary>
|
/// <param name="saveDays">保留天数</param>
|
private static void CleanLogDirectory(int saveDays)
|
{
|
// 获取Log目录路径
|
var logBasePath = Path.Combine(Environment.CurrentDirectory, "Log");
|
|
if (!Directory.Exists(logBasePath))
|
{
|
WriteLog.GetLog("LogJob").Write($"Log目录不存在:{logBasePath}", "LogJob");
|
return;
|
}
|
|
var nowTime = DateTime.Now;
|
var cutoffDate = nowTime.AddDays(-saveDays);
|
|
WriteLog.GetLog("LogJob").Write($"开始清理日志,保留天数:{saveDays},截止日期:{cutoffDate:yyyy-MM-dd}", "LogJob");
|
|
// 获取Log目录下的所有子目录
|
var allSubDirs = Directory.GetDirectories(logBasePath, "*", SearchOption.AllDirectories);
|
|
foreach (var dirPath in allSubDirs)
|
{
|
try
|
{
|
// 获取文件夹名
|
var dirName = Path.GetFileName(dirPath);
|
|
// 尝试解析为日期(支持多种格式)
|
if (TryParseDateFolder(dirName, out DateTime folderDate))
|
{
|
// 判断是否过期
|
if (folderDate < cutoffDate)
|
{
|
WriteLog.GetLog("LogJob").Write($"删除过期日志文件夹:{dirPath},日期:{folderDate:yyyy-MM-dd}", "LogJob");
|
|
// 递归删除文件夹及其内容
|
Directory.Delete(dirPath, true);
|
}
|
else
|
{
|
WriteLog.GetLog("LogJob").Write($"保留日志文件夹:{dirPath},日期:{folderDate:yyyy-MM-dd}", "LogJob");
|
}
|
}
|
}
|
catch (Exception ex)
|
{
|
WriteLog.GetLog("LogJob").Write($"处理文件夹 {dirPath} 时出错:{ex.Message}", "LogJob");
|
}
|
}
|
|
WriteLog.GetLog("LogJob").Write($"日志清理完成", "LogJob");
|
}
|
|
/// <summary>
|
/// 尝试解析日期文件夹名称
|
/// </summary>
|
/// <param name="folderName">文件夹名称</param>
|
/// <param name="date">解析出的日期</param>
|
/// <returns>是否成功解析</returns>
|
private static bool TryParseDateFolder(string folderName, out DateTime date)
|
{
|
// 支持的日期格式
|
string[] dateFormats =
|
{
|
"yyyy-MM-dd", // 2025-12-07
|
"yyyyMMdd", // 20251207
|
"yyyy_MM_dd", // 2025_12_07
|
"yyyy.MM.dd", // 2025.12.07
|
"yyyy年MM月dd日" // 2025年12月07日
|
};
|
|
// 尝试解析日期
|
bool success = DateTime.TryParseExact(
|
folderName,
|
dateFormats,
|
System.Globalization.CultureInfo.InvariantCulture,
|
System.Globalization.DateTimeStyles.None,
|
out date
|
);
|
|
return success;
|
}
|
}
|
}
|