Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OnFileRemoving life cycle hook #106 #107

Merged
merged 4 commits into from
Jul 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/Serilog.Sinks.File/Sinks/File/FileLifecycleHooks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ namespace Serilog.Sinks.File
{
/// <summary>
/// Enables hooking into log file lifecycle events.
/// Hooks run synchronously and therefore may affect responsiveness of the application if long operations are performed.
/// </summary>
public abstract class FileLifecycleHooks
{
Expand All @@ -35,5 +36,12 @@ public abstract class FileLifecycleHooks
/// <param name="encoding">The encoding to use when reading/writing to the stream.</param>
/// <returns>The <see cref="Stream"/> Serilog should use when writing events to the log file.</returns>
public virtual Stream OnFileOpened(Stream underlyingStream, Encoding encoding) => underlyingStream;

/// <summary>
/// Called before an obsolete (rolling) log file is deleted.
/// This can be used to copy old logs to an archive location or send to a backup server.
/// </summary>
/// <param name="path">The full path to the file being deleted.</param>
public virtual void OnFileDeleting(string path) {}
}
}
3 changes: 2 additions & 1 deletion src/Serilog.Sinks.File/Sinks/File/RollingFileSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,12 @@ void ApplyRetentionPolicy(string currentFilePath)
var fullPath = Path.Combine(_roller.LogFileDirectory, obsolete);
try
{
_hooks?.OnFileDeleting(fullPath);
System.IO.File.Delete(fullPath);
}
catch (Exception ex)
{
SelfLog.WriteLine("Error {0} while removing obsolete log file {1}", ex, fullPath);
SelfLog.WriteLine("Error {0} while processing obsolete log file {1}", ex, fullPath);
nogard111 marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions test/Serilog.Sinks.File.Tests/RollingFileSinkTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,28 @@ public void WhenRetentionCountIsSetOldFilesAreDeleted()
});
}

[Fact]
public void WhenRetentionCountAndArchivingHookIsSetOldFilesAreCopiedAndOriginalDeleted()
{
const string archiveDirectory = "OldLogs";
LogEvent e1 = Some.InformationEvent(),
e2 = Some.InformationEvent(e1.Timestamp.AddDays(1)),
e3 = Some.InformationEvent(e2.Timestamp.AddDays(5));

TestRollingEventSequence(
(pf, wt) => wt.File(pf, retainedFileCountLimit: 2, rollingInterval: RollingInterval.Day, hooks: new ArchiveOldLogsHook(archiveDirectory)),
new[] {e1, e2, e3},
files =>
{
Assert.Equal(3, files.Count);
Assert.True(!System.IO.File.Exists(files[0]));
Assert.True(System.IO.File.Exists(files[1]));
Assert.True(System.IO.File.Exists(files[2]));

Assert.True(System.IO.File.Exists(ArchiveOldLogsHook.AddTopDirectory(files[0], archiveDirectory)));
});
}

[Fact]
public void WhenSizeLimitIsBreachedNewFilesCreated()
{
Expand Down
35 changes: 35 additions & 0 deletions test/Serilog.Sinks.File.Tests/Support/ArchiveOldLogsHook.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.IO;
using System.Text;

namespace Serilog.Sinks.File.Tests.Support
{
internal class ArchiveOldLogsHook : FileLifecycleHooks
{
private readonly string _relativeArchiveDir;

public ArchiveOldLogsHook(string relativeArchiveDir)
{
_relativeArchiveDir = relativeArchiveDir;
}

public override void OnFileDeleting(string path)
{
base.OnFileDeleting(path);
var newFile = AddTopDirectory(path, _relativeArchiveDir, true);
System.IO.File.Copy(path, newFile, false);
}

public static string AddTopDirectory(string path, string directoryToAdd, bool createOnNonExist = false)
{
string file = Path.GetFileName(path);
string directory = Path.Combine(Path.GetDirectoryName(path) ?? throw new InvalidOperationException(), directoryToAdd);

if (createOnNonExist && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
return Path.Combine(directory, file);
}
}
}