using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WIDESEAWCS_Common.ServiceLog { public class ServiceLogger { private static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim(); private static string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log\\" + DateTime.Now.ToString("yyyy-MM-dd")); private static int size = 10485760; private static string ext = ".log"; public static void WriteLogToFile(string fileName, string log) { try { LogWriteLock.EnterWriteLock(); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } string path = Path.Combine(folderPath, GetLastAccessFileName(fileName)); DateTime now = DateTime.Now; string contents = $"【{now}】{Environment.NewLine}{log}"; File.AppendAllText(path, contents); } catch { } finally { LogWriteLock.ExitWriteLock(); } } private static string GetLogFilePath(string folderPath, string fileName) { string fileName2 = fileName; List list = (from fi in new DirectoryInfo(folderPath).GetFiles() where fi.Name.ToLower().Contains(fileName2.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size select fi into d orderby d.Name descending select d).ToList(); if (list.Count > 0) { return list.FirstOrDefault().FullName; } return Path.Combine(folderPath, fileName2 + "_" + DateTime.Now.ToString("HH-mm-ss") + ".log"); } private static string GetLastAccessFileName(string fileName) { string[] existLogFileNames = GetExistLogFileNames(fileName); foreach (string text in existLogFileNames) { if (new FileInfo(text).Length < size) { return text; } } return fileName + "_" + DateTime.Now.ToString("HH-mm-ss") + ".log"; } public static string[] GetExistLogFileNames(string fileName) { return Directory.GetFiles(folderPath, fileName + "*.log"); } } }