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.
BookingHeChuan/Myshipping.Core/EventSubscriber/LogZipClearSubscriber.cs

94 lines
3.4 KiB
C#

using Furion.EventBus;
using Myshipping.Core.Entity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;
using System.Linq;
using Furion;
using Furion.Logging;
namespace Myshipping.Core;
public class LogZipClearSubscriber : IEventSubscriber
{
public LogZipClearSubscriber(IServiceProvider services)
{
Services = services;
}
public IServiceProvider Services { get; }
[EventSubscribe("LogZipClear:DoWork")]
public async Task DoWork(EventHandlerExecutingContext context)
{
var logBaseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
var subDirs = new string[] {
Path.Combine(logBaseDir,"error"),
Path.Combine(logBaseDir,"info"),
Path.Combine(logBaseDir,"warn")
};
//留3天的不压缩处理
var skipDate = new string[] {
DateTime.Today.ToString("yyyyMMdd"),
DateTime.Today.AddDays(-1).ToString("yyyyMMdd"),
DateTime.Today.AddDays(-2).ToString("yyyyMMdd")
};
//压缩日志
Log.Information($"准备压缩日志文件……");
foreach (var dir in subDirs)
{
var files = new List<string>(Directory.GetFiles(dir, "*.log"));
var fileDateList = files.GroupBy(x => Path.GetFileName(x).Substring(0, Path.GetFileName(x).IndexOf("_"))).Select(x => x.Key).Where(x => !skipDate.Contains(x)).ToList();
foreach (var fd in fileDateList)
{
var zipFile = Path.Combine(dir, $"{fd}.zip");
var listToZip = files.Where(x => Path.GetFileName(x).Substring(0, Path.GetFileName(x).IndexOf("_")) == fd).ToList();
using (FileStream fs = new FileStream(zipFile, FileMode.Create, FileAccess.ReadWrite))
{
using (ZipOutputStream zipOut = new ZipOutputStream(fs))
{
foreach (var f in listToZip)
{
var fn = Path.GetFileName(f);
var fileDate = fn.Substring(0, fn.IndexOf("_"));
ZipEntry zipEntry = new ZipEntry(fn);
zipOut.PutNextEntry(zipEntry);
await zipOut.WriteAsync(File.ReadAllBytes(f));
await zipOut.FlushAsync();
File.Delete(f);
}
}
}
Log.Information($"已将{fd}的日志压缩,共{listToZip.Count}个文件");
}
}
//清理过期
Log.Information($"准备清理过期日志文件……");
var dtExpire = DateTime.Today.AddDays(-60);
foreach (var dir in subDirs)
{
var files = new List<string>(Directory.GetFiles(dir, "*.zip"));
foreach (var file in files)
{
var fileDate = DateTime.ParseExact(Path.GetFileNameWithoutExtension(file), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
if (fileDate < dtExpire)
{
File.Delete(file);
Log.Information($"已删除过期日志文件:{Path.GetFileName(file)}");
}
}
}
}
}