LogNetFileSize.cs
4.06 KB
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
using System;
using System.IO;
namespace HslCommunication.LogNet
{
/// <summary>
/// 根据文件的大小来存储日志信息
/// </summary>
/// <remarks>
/// 此日志的实例是根据文件的大小储存,例如设置了2M,每隔2M,系统将生成一个新的日志文件。
/// </remarks>
public class LogNetFileSize : LogNetBase, ILogNet
{
#region Constructor
/// <summary>
/// 实例化一个根据文件大小生成新文件的
/// </summary>
/// <param name="filePath">日志文件的保存路径</param>
/// <param name="fileMaxSize">每个日志文件的最大大小,默认2M</param>
public LogNetFileSize(string filePath, int fileMaxSize = 2 * 1024 * 1024)
{
m_filePath = filePath;
m_fileMaxSize = fileMaxSize;
LogSaveMode = LogNetManagment.LogSaveModeByFileSize;
m_filePath = CheckPathEndWithSprit(m_filePath);
}
#endregion
#region LogNetBase Override
/// <summary>
/// 获取需要保存的日志文件
/// </summary>
/// <returns>字符串数据</returns>
protected override string GetFileSaveName()
{
//路径没有设置则返回空
if (string.IsNullOrEmpty(m_filePath)) return string.Empty;
if (string.IsNullOrEmpty(m_fileName))
{
//加载文件名称
m_fileName = GetLastAccessFileName();
}
if (File.Exists(m_fileName))
{
FileInfo fileInfo = new FileInfo(m_fileName);
if (fileInfo.Length > m_fileMaxSize)
{
//新生成文件
m_fileName = GetDefaultFileName();
}
}
return m_fileName;
}
#endregion
#region Public Method
/// <summary>
/// 返回所有的日志文件
/// </summary>
/// <returns>所有的日志文件信息</returns>
public string[] GetExistLogFileNames()
{
if (!string.IsNullOrEmpty(m_filePath))
{
return Directory.GetFiles(m_filePath, LogNetManagment.LogFileHeadString + "*.txt");
}
else
{
return new string[] { };
}
}
#endregion
#region Private Method
/// <summary>
/// 获取之前保存的日志文件
/// </summary>
/// <returns></returns>
private string GetLastAccessFileName()
{
foreach (var m in GetExistLogFileNames())
{
FileInfo fileInfo = new FileInfo(m);
if (fileInfo.Length < m_fileMaxSize)
{
m_CurrentFileSize = (int)fileInfo.Length;
return m;
}
}
//返回一个新的默认当前时间的日志名称
return GetDefaultFileName();
}
/// <summary>
/// 获取一个新的默认的文件名称
/// </summary>
/// <returns></returns>
private string GetDefaultFileName()
{
//返回一个新的默认当前时间的日志名称
return m_filePath + LogNetManagment.LogFileHeadString + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
}
#endregion
#region Private Member
private string m_fileName = string.Empty; // 当前正在存储的文件名
private string m_filePath = string.Empty; // 存储文件的路径
private int m_fileMaxSize = 2 * 1024 * 1024; //2M
private int m_CurrentFileSize = 0;
#endregion
#region Object Override
/// <summary>
/// 返回表示当前对象的字符串
/// </summary>
/// <returns>字符串数据</returns>
public override string ToString()
{
return $"LogNetFileSize[{m_fileMaxSize}]";
}
#endregion
}
}