Dispenser/DispenserCore/Job/LogUploadJob.cs

57 lines
2.0 KiB
C#
Raw Permalink Normal View History

2024-08-16 07:20:09 +00:00
using System.IO.Compression;
using DispenserCore.Service;
using Quartz;
using Serilog;
namespace DispenserCore.Job;
public class LogUploadJob : IJob
{
private static LogParamsService _logParamsService = new();
public Task Execute(IJobExecutionContext context)
{
var logParams = _logParamsService.GetLogParams();
var basePath = logParams!.Path ?? AppDomain.CurrentDomain.BaseDirectory;
//前一天的日期
var date = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
var levels = logParams.UploadLevels!.Split(",").ToList();
string? sourceFolder = null;
string? zipFilePath = null;
foreach (var level in levels)
try
{
sourceFolder = Path.Combine(basePath, "logs", level);
zipFilePath = Path.Combine(sourceFolder, $"{level}-{date}.log");
var searchPattern = $"*{level}-{date}*.log";
using (var zipFile = new FileStream(zipFilePath, FileMode.Create))
{
using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Create))
{
foreach (var file in Directory.GetFiles(sourceFolder, searchPattern))
{
var fileName = Path.GetFileName(file);
var entry = archive.CreateEntry(fileName);
using (var entryStream = entry.Open())
using (var fileStream = File.OpenRead(file))
{
fileStream.CopyTo(entryStream);
}
}
}
}
//TODO 上传到云端
}
catch (Exception e)
{
Log.Error(e, "日志{0}上传失败", sourceFolder);
}
finally
{
if (zipFilePath != null && File.Exists(zipFilePath)) File.Delete(zipFilePath);
}
return Task.CompletedTask;
}
}