-
Notifications
You must be signed in to change notification settings - Fork 10
/
RollingFileSink.cs
298 lines (262 loc) · 10.8 KB
/
RollingFileSink.cs
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright 2013-2017 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Linq;
using System.Text;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Formatting;
namespace Serilog.Sinks.File
{
sealed class RollingFileSink : ILogEventSink, IFlushableFileSink, IDisposable
{
readonly PathRoller _roller;
readonly ITextFormatter _textFormatter;
readonly long? _fileSizeLimitBytes;
readonly int? _retainedFileCountLimit;
readonly Encoding _encoding;
readonly bool _buffered;
readonly bool _shared;
readonly bool _rollOnFileSizeLimit;
readonly FileLifecycleHooks _hooks;
readonly bool _keepFilename;
readonly object _syncRoot = new object();
bool _isDisposed;
DateTime? _nextCheckpoint;
IFileSink _currentFile;
int? _currentFileSequence;
public RollingFileSink(string path,
ITextFormatter textFormatter,
long? fileSizeLimitBytes,
int? retainedFileCountLimit,
Encoding encoding,
bool buffered,
bool shared,
RollingInterval rollingInterval,
bool rollOnFileSizeLimit,
FileLifecycleHooks hooks,
bool keepFilename = false)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) throw new ArgumentException("Negative value provided; file size limit must be non-negative.");
if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1.");
_roller = new PathRoller(path, rollingInterval);
_textFormatter = textFormatter;
_fileSizeLimitBytes = fileSizeLimitBytes;
_retainedFileCountLimit = retainedFileCountLimit;
_encoding = encoding;
_buffered = buffered;
_shared = shared;
_rollOnFileSizeLimit = rollOnFileSizeLimit;
_hooks = hooks;
_keepFilename = keepFilename;
}
public void Emit(LogEvent logEvent)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
lock (_syncRoot)
{
if (_isDisposed) throw new ObjectDisposedException("The log file has been disposed.");
var now = Clock.DateTimeNow;
AlignCurrentFileTo(now);
while (_currentFile?.EmitOrOverflow(logEvent) == false && _rollOnFileSizeLimit)
{
AlignCurrentFileTo(now, nextSequence: true);
}
}
}
void AlignCurrentFileTo(DateTime now, bool nextSequence = false)
{
if (!_nextCheckpoint.HasValue)
{
OpenFile(now);
}
else if (nextSequence || now >= _nextCheckpoint.Value)
{
int? minSequence = null;
if (nextSequence)
{
if (_currentFileSequence == null)
minSequence = 1;
else
minSequence = _currentFileSequence.Value + 1;
}
CloseFile();
OpenFile(now, minSequence);
}
}
void OpenFile(DateTime now, int? minSequence = null)
{
var currentCheckpoint = _roller.GetCurrentCheckpoint(now);
// We only try periodically because repeated failures
// to open log files REALLY slow an app down.
_nextCheckpoint = _roller.GetNextCheckpoint(now) ?? now.AddMinutes(30);
var existingFiles = Enumerable.Empty<string>();
try
{
if (Directory.Exists(_roller.LogFileDirectory))
{
existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
.Select(Path.GetFileName);
}
}
catch (DirectoryNotFoundException) { }
var latestForThisCheckpoint = _roller
.SelectMatches(existingFiles)
.Where(m => m.DateTime == currentCheckpoint)
.OrderByDescending(m => m.SequenceNumber)
.FirstOrDefault();
var sequence = latestForThisCheckpoint?.SequenceNumber;
if (minSequence != null)
{
if (sequence == null || sequence.Value < minSequence.Value)
sequence = minSequence;
}
if (_keepFilename)
{
const int maxAttempts = 3;
// if current file exists we rename it with rolling date
_roller.GetLogFilePath(out var currentPath);
if (System.IO.File.Exists(currentPath) && new FileInfo(currentPath).Length > 0)
{
for (var attempt = 0; attempt < maxAttempts; attempt++)
{
_roller.GetLogFilePath(now, sequence, out var path);
try
{
System.IO.File.Move(currentPath, path);
_currentFileSequence = sequence;
}
catch (IOException ex)
{
if (IOErrors.IsLockedFile(ex))
{
SelfLog.WriteLine("File target {0} was locked, attempting to open next in sequence (attempt {1})", path, attempt + 1);
sequence = (sequence ?? 0) + 1;
continue;
}
throw;
}
ApplyRetentionPolicy(path);
break;
}
}
//now we open the current file
try
{
_currentFile = _shared ?
#pragma warning disable 618
(IFileSink)new SharedFileSink(currentPath, _textFormatter, _fileSizeLimitBytes, _encoding) :
#pragma warning restore 618
new FileSink(currentPath, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered, _hooks);
}
catch (IOException ex)
{
if (IOErrors.IsLockedFile(ex))
{
SelfLog.WriteLine("File target {0} was locked, attempting to open next in sequence ", currentPath);
}
throw;
}
}
else
{
const int maxAttempts = 3;
for (var attempt = 0; attempt < maxAttempts; attempt++)
{
_roller.GetLogFilePath(now, sequence, out var path);
try
{
_currentFile = _shared ?
#pragma warning disable 618
(IFileSink)new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding) :
#pragma warning restore 618
new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered, _hooks);
_currentFileSequence = sequence;
}
catch (IOException ex)
{
if (IOErrors.IsLockedFile(ex))
{
SelfLog.WriteLine("File target {0} was locked, attempting to open next in sequence (attempt {1})", path, attempt + 1);
sequence = (sequence ?? 0) + 1;
continue;
}
throw;
}
ApplyRetentionPolicy(path);
return;
}
}
}
void ApplyRetentionPolicy(string currentFilePath)
{
if (_retainedFileCountLimit == null) return;
var currentFileName = Path.GetFileName(currentFilePath);
// We consider the current file to exist, even if nothing's been written yet,
// because files are only opened on response to an event being processed.
var potentialMatches = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
.Select(Path.GetFileName)
.Union(new [] { currentFileName });
var newestFirst = _roller
.SelectMatches(potentialMatches)
.OrderByDescending(m => m.DateTime)
.ThenByDescending(m => m.SequenceNumber)
.Select(m => m.Filename);
var toRemove = newestFirst
.Where(n => StringComparer.OrdinalIgnoreCase.Compare(currentFileName, n) != 0)
.Skip(_retainedFileCountLimit.Value - 1)
.ToList();
foreach (var obsolete in toRemove)
{
var fullPath = Path.Combine(_roller.LogFileDirectory, obsolete);
try
{
System.IO.File.Delete(fullPath);
}
catch (Exception ex)
{
SelfLog.WriteLine("Error {0} while removing obsolete log file {1}", ex, fullPath);
}
}
}
public void Dispose()
{
lock (_syncRoot)
{
if (_currentFile == null) return;
CloseFile();
_isDisposed = true;
}
}
void CloseFile()
{
if (_currentFile != null)
{
(_currentFile as IDisposable)?.Dispose();
_currentFile = null;
}
_nextCheckpoint = null;
}
public void FlushToDisk()
{
lock (_syncRoot)
{
_currentFile?.FlushToDisk();
}
}
}
}