刘磊
2024-12-21 a6ea79849f0142b5280f0c5d4b15ecc83f0d015a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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;
        }
    }
}