TimestampedRollingFileSink.cs
7.8 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
using System.Text;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Formatting.Display;
namespace Rcs.Api.Logging;
public sealed class TimestampedRollingFileSink : ILogEventSink, IDisposable
{
private readonly object _syncRoot = new();
private readonly string _logsPath;
private readonly string _filePrefix;
private readonly long _fileSizeLimitBytes;
private readonly int _retentionDays;
private readonly Encoding _encoding;
private readonly MessageTemplateTextFormatter _formatter;
private StreamWriter? _writer;
private string? _currentFilePath;
private long _currentFileSizeBytes;
private bool _disposed;
public TimestampedRollingFileSink(
string logsPath,
string filePrefix,
long fileSizeLimitBytes,
int retentionDays,
string outputTemplate)
{
if (string.IsNullOrWhiteSpace(logsPath))
{
throw new ArgumentException("logsPath cannot be null or empty.", nameof(logsPath));
}
if (string.IsNullOrWhiteSpace(filePrefix))
{
throw new ArgumentException("filePrefix cannot be null or empty.", nameof(filePrefix));
}
if (fileSizeLimitBytes <= 0)
{
throw new ArgumentOutOfRangeException(nameof(fileSizeLimitBytes), "fileSizeLimitBytes must be greater than 0.");
}
if (retentionDays <= 0)
{
throw new ArgumentOutOfRangeException(nameof(retentionDays), "retentionDays must be greater than 0.");
}
_logsPath = logsPath;
_filePrefix = filePrefix;
_fileSizeLimitBytes = fileSizeLimitBytes;
_retentionDays = retentionDays;
_encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
_formatter = new MessageTemplateTextFormatter(outputTemplate, null);
Directory.CreateDirectory(_logsPath);
CleanupExpiredFiles();
if (!TryOpenExistingWritableFile())
{
RollFile();
}
}
public void Emit(LogEvent logEvent)
{
if (_disposed)
{
return;
}
lock (_syncRoot)
{
try
{
if (_writer == null)
{
RollFile();
}
using var renderedWriter = new StringWriter();
_formatter.Format(logEvent, renderedWriter);
var rendered = renderedWriter.ToString();
var renderedBytes = _encoding.GetByteCount(rendered);
// Keep the first file available for startup even if a single event is oversized.
if (_currentFileSizeBytes > 0 && _currentFileSizeBytes + renderedBytes > _fileSizeLimitBytes)
{
RollFile();
}
_writer!.Write(rendered);
_writer.Flush();
_currentFileSizeBytes += renderedBytes;
}
catch (Exception ex)
{
SelfLog.WriteLine("TimestampedRollingFileSink emit failed: {0}", ex);
}
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
lock (_syncRoot)
{
_disposed = true;
_writer?.Dispose();
_writer = null;
_currentFilePath = null;
_currentFileSizeBytes = 0;
}
}
private void RollFile()
{
_writer?.Dispose();
_writer = null;
var filePath = CreateUniqueLogFilePath();
var stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read);
_writer = new StreamWriter(stream, _encoding);
_currentFilePath = filePath;
_currentFileSizeBytes = 0;
CleanupExpiredFiles();
}
private bool TryOpenExistingWritableFile()
{
try
{
var candidates = Directory.GetFiles(_logsPath, $"{_filePrefix}-*.log")
.Select(file => new FileInfo(file))
.Where(file => file.Length < _fileSizeLimitBytes)
.OrderByDescending(file => GetSortTimestamp(file));
foreach (var candidate in candidates)
{
try
{
var stream = new FileStream(candidate.FullName, FileMode.Append, FileAccess.Write, FileShare.Read);
_writer = new StreamWriter(stream, _encoding);
_currentFilePath = candidate.FullName;
_currentFileSizeBytes = candidate.Length;
return true;
}
catch (Exception ex)
{
SelfLog.WriteLine("TimestampedRollingFileSink open existing file failed ({0}): {1}", candidate.FullName, ex);
}
}
}
catch (Exception ex)
{
SelfLog.WriteLine("TimestampedRollingFileSink scan existing files failed: {0}", ex);
}
return false;
}
private DateTime GetSortTimestamp(FileInfo fileInfo)
{
return TryGetLogFileTimestamp(fileInfo.FullName, out var timestamp)
? timestamp
: fileInfo.LastWriteTime;
}
private string CreateUniqueLogFilePath()
{
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var baseName = $"{_filePrefix}-{timestamp}";
var filePath = Path.Combine(_logsPath, $"{baseName}.log");
var sequence = 1;
while (File.Exists(filePath))
{
filePath = Path.Combine(_logsPath, $"{baseName}_{sequence:000}.log");
sequence++;
}
return filePath;
}
private void CleanupExpiredFiles()
{
try
{
var cutoff = DateTime.Now.AddDays(-_retentionDays);
var files = Directory.GetFiles(_logsPath, $"{_filePrefix}-*.log")
.ToList();
foreach (var file in files)
{
// Never delete the active file.
if (string.Equals(file, _currentFilePath, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (TryGetLogFileTimestamp(file, out var fileTimestamp))
{
if (fileTimestamp < cutoff)
{
File.Delete(file);
}
continue;
}
// Fallback for files that do not match the naming pattern.
if (File.GetCreationTime(file) < cutoff)
{
File.Delete(file);
}
}
}
catch (Exception ex)
{
SelfLog.WriteLine("TimestampedRollingFileSink cleanup failed: {0}", ex);
}
}
private bool TryGetLogFileTimestamp(string filePath, out DateTime timestamp)
{
timestamp = default;
var fileName = Path.GetFileNameWithoutExtension(filePath);
if (string.IsNullOrWhiteSpace(fileName))
{
return false;
}
var prefix = $"{_filePrefix}-";
if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
var core = fileName[prefix.Length..];
var underscoreIndex = core.IndexOf('_');
if (underscoreIndex < 0)
{
return false;
}
// Strip optional sequence suffix (e.g. _001).
var secondUnderscore = core.IndexOf('_', underscoreIndex + 1);
var timeToken = secondUnderscore >= 0 ? core[..secondUnderscore] : core;
return DateTime.TryParseExact(
timeToken,
"yyyyMMdd_HHmmss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out timestamp);
}
}