分支自 SuZhouGuanHong/TaiYuanTaiZhong

dengjunjie
2024-05-19 429bb4abbaea6fd6be33dcf62735d4ada5070b63
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Json;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Extensions;
 
namespace WIDESEA_Comm.LogInfo
{
    /// <summary>
    /// 日志写入
    /// </summary>
    public partial class WriteLog
    {
        private int fileSize;
        public static WriteLog log;
        static string EquipName;
        private string logFileName;
        public string FileLogPath { set; get; }
        /// <summary>
        /// 写入日志(不要多线程操作同一文件,一个设备一个文件夹)
        /// </summary>
        public static void Write_Log(string groupName, string logName, string content, object data = null)
        {
            string basePath = System.Environment.CurrentDirectory + "/Log/" + $"/{groupName}/{DateTime.Now.ToString("yyyy_MM_dd")}";
 
            #region 删除文件夹内指定日期前文件夹
            string name = Environment.CurrentDirectory + "/Log/" + $"/{groupName}";
            if (Directory.Exists(name))
                DeleteFoldersOlderThan(name, DateTime.Now.AddDays(-30));
            #endregion
 
            //如果日志文件目录不存在,则创建
            if (!Directory.Exists(basePath))
            {
                Directory.CreateDirectory(basePath);
            }
            try
            {
                FileStream fs = new FileStream(basePath + "/" + logName + $"_{DateTime.Now.ToString("yyyy_MM_dd")}_Log.txt", FileMode.Append);
                StreamWriter strwriter = new StreamWriter(fs);
                try
                {
                    DateTime d = DateTime.Now;
                    strwriter.WriteLine(d.ToString());
                    strwriter.WriteLine(content);
                    if (data != null)
                    {
                        //strwriter.WriteLine(JsonConvert.SerializeObject(data));
                        strwriter.WriteLine(data);
                    }
                    strwriter.WriteLine("-------------------------------");
                    strwriter.WriteLine();
                    strwriter.Flush();
                }
                catch { }
                finally
                {
                    strwriter.Close();
                    fs.Close();
                }
            }
            catch { }
        }
        public static WriteLog Info(string equipName)
        {
            EquipName = equipName;
            //if (log == null)
            log = new WriteLog("Info" + equipName);
            log.FileLogPath = AppContext.BaseDirectory + "\\log\\Info\\" + DateTime.Now.ToString("yyyyMMdd") /*+ "\\" + EquipName + "_" + DateTime.Now.ToString("yyyyMMdd")*/ + "\\";
 
            #region 删除文件夹内指定日期前文件夹
            string name = AppContext.BaseDirectory + "\\log\\Info\\";
            if (Directory.Exists(name))
                DeleteFoldersOlderThan(name, DateTime.Now.AddDays(-30));
            #endregion
 
            return log;
        }
        private WriteLog(string equipName)
        {
            //初始化大于399M日志文件将自动删除;
 
            this.fileSize = 2048 * 1024 * 200;//50M   2048 * 1024 * 200= 419430000字节(b)=399.9996185兆字节(mb)
 
            //默认路径
 
            //this.FileLogPath = AppContext.BaseDirectory + "\\log\\" + EquipName + "\\";
            EquipName = equipName;
            if (!string.IsNullOrEmpty(equipName))
                this.logFileName = equipName + "_log" + DateTime.Now.ToString("yyyyMMdd") + ".log";
            else
                this.logFileName = "log" + DateTime.Now.ToString("yyyyMMdd") + ".log";
            //this.logFileName = EquipName + "_log" + DateTime.Now.ToString("yyyyMMdd") + ".log";
        }
        object flag = new object();
        public void Write(string Message, string equipName)
        {
            lock (flag)
            {
                if (!string.IsNullOrEmpty(equipName))
                    this.logFileName = equipName + "_log" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                else
                    this.logFileName = "log" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                this.Write(this.logFileName, Message, equipName);
            }
        }
        public void Write(string LogFileName, string Message, string equipName)
        {
 
            //DirectoryInfo path=new DirectoryInfo(LogFileName);
            //如果日志文件目录不存在,则创建
            if (!Directory.Exists(this.FileLogPath))
            {
                Directory.CreateDirectory(this.FileLogPath);
            }
 
            FileInfo finfo = new FileInfo(this.FileLogPath + LogFileName);
            if (finfo.Exists && finfo.Length > fileSize)
            {
                finfo.Delete();
            }
            try
            {
                FileStream fs = new FileStream(this.FileLogPath + LogFileName, FileMode.Append);
                StreamWriter strwriter = new StreamWriter(fs);
                try
                {
 
                    DateTime d = DateTime.Now;
                    strwriter.WriteLine("时间:" + d.ToString());
                    strwriter.WriteLine(Message);
                    strwriter.WriteLine();
                    strwriter.Flush();
                }
                catch (Exception ee)
                {
                    //Console.WriteLine("日志文件写入失败信息:" + ee.ToString());
                }
                finally
                {
                    strwriter.Close();
                    strwriter = null;
                    fs.Close();
                    fs = null;
                }
            }
            catch (Exception ee)
            {
                //Console.WriteLine("日志文件没有打开,详细信息如下:");
            }
        }
 
        #region 自动清除日志
 
        /// <summary>
        /// 删除文件夹内指定日期前文件夹
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="cutOffDate"></param>
        public static void DeleteFoldersOlderThan(string folderPath, DateTime cutOffDate)
        {
            DirectoryInfo di = new DirectoryInfo(folderPath);
            foreach (DirectoryInfo subDir in di.GetDirectories())
            {
                // 获取文件夹的最后访问时间
                DateTime lastAccess = subDir.CreationTime;
                //DateTime lastAccess = subDir.LastAccessTime;
 
                // 如果文件夹的最后访问时间早于或等于截止日期,则删除该文件夹
                if (lastAccess <= cutOffDate)
                {
                    try
                    {
                        Directory.Delete(subDir.FullName, true); // 递归删除文件夹及其内容
                        //Console.WriteLine($"文件 {subDir.FullName} 已删除。");
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine($"无法删除文件 {subDir.FullName}: {ex.Message}");
                    }
                }
            }
        }
 
        /// <summary>
        /// 删除文件夹内指定日期前文件
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <param name="cutOffDate"></param>
        public static void DeleteFilesOlderThan(string directoryPath, DateTime cutOffDate)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
 
            // 获取所有文件并筛选出创建日期在指定日期之前的文件
            FileInfo[] filesToDelete = directoryInfo.GetFiles()
                .Where(f => f.CreationTime < cutOffDate).ToArray();
 
            foreach (FileInfo file in filesToDelete)
            {
                try
                {
                    file.Delete(); // 删除文件
                    Console.WriteLine($"文件 {file.FullName} 已删除。");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"无法删除文件 {file.FullName}: {ex.Message}");
                }
            }
        }
 
        //public static void Main()
        //{
        //    string path = @"C:\YourDirectoryPath"; // 替换为你的目录路径
        //    DateTime cutOff = new DateTime(2023, 3, 31); // 设置删除文件的截止日期
        //    DeleteFilesOlderThan(path, cutOff);
        //}
        #endregion
    }
}