blob: e155858f4b17f75507ad2440f59f51fcd24f4146 (
plain)
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
|
using System.Text;
namespace Agent.App.Logging;
internal sealed class RollingFileWriter : IDisposable
{
private readonly object _sync = new();
private readonly string _path;
private readonly long _maxBytes;
private readonly int _retainedFiles;
private StreamWriter _writer;
public RollingFileWriter(string path, long maxBytes, int retainedFiles)
{
_path = path;
_maxBytes = maxBytes;
_retainedFiles = retainedFiles;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
_writer = Open();
}
public void WriteLine(string line)
{
lock (_sync)
{
if (_writer.BaseStream.Length >= _maxBytes) Rotate();
_writer.WriteLine(line);
_writer.Flush();
}
}
private StreamWriter Open() => new(new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.Read), new UTF8Encoding(false));
private void Rotate()
{
_writer.Dispose();
for (int index = _retainedFiles - 1; index >= 1; index--)
{
string source = $"{_path}.{index}";
if (File.Exists(source)) File.Move(source, $"{_path}.{index + 1}", true);
}
if (File.Exists(_path)) File.Move(_path, $"{_path}.1", true);
_writer = Open();
}
public void Dispose()
{
lock (_sync) _writer.Dispose();
}
}
|