Dreamine.Logging 1.0.2
Dreamine.Logging 프로젝트의 API와 구성 요소를 제공합니다.
로딩중...
검색중...
일치하는것 없음
TextFileLogSink.cs
이 파일의 문서화 페이지로 가기
1using System;
2using System.IO;
3using System.Text;
6
8{
25 public sealed class TextFileLogSink : IDreamineLogSink, IDisposable
26 {
35 private const int DefaultFlushEveryWriteCount = 20;
36
45 private readonly object _syncRoot = new();
54 private readonly string _logDirectory;
72 private readonly int _flushEveryWriteCount;
81 private StreamWriter? _writer;
90 private string? _currentFilePath;
99 private int _pendingFlushCount;
108 private bool _disposed;
109
151 string logDirectory,
152 IDreamineLogFormatter formatter,
153 int flushEveryWriteCount = DefaultFlushEveryWriteCount)
154 {
155 _logDirectory = string.IsNullOrWhiteSpace(logDirectory)
156 ? "Logs"
157 : logDirectory;
158
159 _formatter = formatter ?? throw new ArgumentNullException(nameof(formatter));
160 _flushEveryWriteCount = flushEveryWriteCount <= 0
162 : flushEveryWriteCount;
163 }
164
189 public void Write(DreamineLogEntry entry)
190 {
191 ArgumentNullException.ThrowIfNull(entry);
192
193 lock (_syncRoot)
194 {
195 if (_disposed)
196 {
197 return;
198 }
199
200 var filePath = GetFilePath(entry.Timestamp);
201 EnsureWriter(filePath);
202
203 var text = _formatter.Format(entry);
204
205 _writer!.WriteLine(text);
207
209 || entry.Level >= DreamineLogLevel.Error)
210 {
211 FlushCore();
212 }
213 }
214 }
215
224 public void Dispose()
225 {
226 lock (_syncRoot)
227 {
228 if (_disposed)
229 {
230 return;
231 }
232
233 try
234 {
235 FlushCore();
236 }
237 catch
238 {
239 // Suppress flush errors during dispose.
240 }
241
242 _writer?.Dispose();
243 _writer = null;
244 _disposed = true;
245 }
246 }
247
272 private string GetFilePath(DateTimeOffset timestamp)
273 {
274 Directory.CreateDirectory(_logDirectory);
275 return Path.Combine(_logDirectory, $"{timestamp:yyyy-MM-dd}.log");
276 }
277
294 private void EnsureWriter(string filePath)
295 {
296 if (_writer is not null
297 && string.Equals(_currentFilePath, filePath, StringComparison.OrdinalIgnoreCase))
298 {
299 return;
300 }
301
302 // Date rolled over (or first write) — close the previous file and open the new one.
303 FlushCore();
304 _writer?.Dispose();
305
306 _currentFilePath = filePath;
307 _writer = new StreamWriter(
308 new FileStream(
309 filePath,
310 FileMode.Append,
311 FileAccess.Write,
312 FileShare.ReadWrite),
313 Encoding.UTF8)
314 {
315 AutoFlush = false
316 };
317 }
318
327 private void FlushCore()
328 {
329 if (_writer is null)
330 {
332 return;
333 }
334
335 _writer.Flush();
337 }
338 }
339}
void Write(DreamineLogEntry entry)
TextFileLogSink(string logDirectory, IDreamineLogFormatter formatter, int flushEveryWriteCount=DefaultFlushEveryWriteCount)
string GetFilePath(DateTimeOffset timestamp)
readonly IDreamineLogFormatter _formatter