Skip to content

Commit f6d1cff

Browse files
Marcin_OsadaMarcin_Osada
Marcin_Osada
authored and
Marcin_Osada
committed
Add test
1 parent 735efa9 commit f6d1cff

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

test/Serilog.Sinks.File.Tests/RollingFileSinkTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,28 @@ public void WhenRetentionCountIsSetOldFilesAreDeleted()
7171
});
7272
}
7373

74+
[Fact]
75+
public void WhenRetentionCountAndArchivingHookIsSetOldFilesAreCopiedAndOriginalDeleted()
76+
{
77+
const string archiveDirectory = "OldLogs";
78+
LogEvent e1 = Some.InformationEvent(),
79+
e2 = Some.InformationEvent(e1.Timestamp.AddDays(1)),
80+
e3 = Some.InformationEvent(e2.Timestamp.AddDays(5));
81+
82+
TestRollingEventSequence(
83+
(pf, wt) => wt.File(pf, retainedFileCountLimit: 2, rollingInterval: RollingInterval.Day, hooks: new ArchiveOldLogsHook(archiveDirectory)),
84+
new[] {e1, e2, e3},
85+
files =>
86+
{
87+
Assert.Equal(3, files.Count);
88+
Assert.True(!System.IO.File.Exists(files[0]));
89+
Assert.True(System.IO.File.Exists(files[1]));
90+
Assert.True(System.IO.File.Exists(files[2]));
91+
92+
Assert.True(System.IO.File.Exists(ArchiveOldLogsHook.AddTopDirectory(files[0], archiveDirectory)));
93+
});
94+
}
95+
7496
[Fact]
7597
public void WhenSizeLimitIsBreachedNewFilesCreated()
7698
{
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System;
2+
using System.IO;
3+
using System.Text;
4+
5+
namespace Serilog.Sinks.File.Tests.Support
6+
{
7+
internal class ArchiveOldLogsHook : FileLifecycleHooks
8+
{
9+
private readonly string _relativeArchiveDir;
10+
11+
public ArchiveOldLogsHook(string relativeArchiveDir)
12+
{
13+
_relativeArchiveDir = relativeArchiveDir;
14+
}
15+
16+
public override void OnFileDeleting(string path)
17+
{
18+
base.OnFileDeleting(path);
19+
var newFile = AddTopDirectory(path, _relativeArchiveDir, true);
20+
System.IO.File.Copy(path, newFile, false);
21+
}
22+
23+
public static string AddTopDirectory(string path, string directoryToAdd, bool createOnNonExist = false)
24+
{
25+
string file = Path.GetFileName(path);
26+
string directory = Path.Combine(Path.GetDirectoryName(path) ?? throw new InvalidOperationException(), directoryToAdd);
27+
28+
if (createOnNonExist && !Directory.Exists(directory))
29+
{
30+
Directory.CreateDirectory(directory);
31+
}
32+
return Path.Combine(directory, file);
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)