using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WIDESEAWCS_Core.Helper; namespace WIDESEAWCS_Core.LogHelper { public class QuartzLogger { static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim(); static string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Log\\{DateTime.Now.ToString("yyyy-MM-dd")}"); public static void WriteLogToFile(string fileName, string log) { try { LogWriteLock.EnterWriteLock(); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } string logFilePath = Path.Combine(folderPath, GetLastAccessFileName(fileName)); DateTime now = DateTime.Now; string logContent = $"【{now}】{Environment.NewLine}{log}"; File.AppendAllText(logFilePath, logContent); } catch { } finally { LogWriteLock.ExitWriteLock(); } } static int size = 10 * 1024 * 1024; static string ext = ".log"; private static string GetLogFilePath(string folderPath, string fileName) { var allFiles = new DirectoryInfo(folderPath); var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(fileName.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList(); if (selectFiles.Count > 0) { return selectFiles.FirstOrDefault().FullName; } return Path.Combine(folderPath, $@"{fileName}_{DateTime.Now.ToString("HH-mm-ss")}.log"); } private static string GetLastAccessFileName(string fileName) { foreach (var m in GetExistLogFileNames(fileName)) { FileInfo fileInfo = new FileInfo(m); if (fileInfo.Length < size) { return m; } } // 返回一个新的默认当前时间的日志名称 return $@"{fileName}_{DateTime.Now.ToString("HH-mm-ss")}.log"; } public static string[] GetExistLogFileNames(string fileName) { string[] fileNames = Directory.GetFiles(folderPath, fileName + "*.log"); return fileNames; } } }