Serilog.Sinks.File.Archive 1.2.0

dotnet add package Serilog.Sinks.File.Archive --version 1.2.0
                    
NuGet\Install-Package Serilog.Sinks.File.Archive -Version 1.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Serilog.Sinks.File.Archive" Version="1.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Serilog.Sinks.File.Archive" Version="1.2.0" />
                    
Directory.Packages.props
<PackageReference Include="Serilog.Sinks.File.Archive" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Serilog.Sinks.File.Archive --version 1.2.0
                    
#r "nuget: Serilog.Sinks.File.Archive, 1.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Serilog.Sinks.File.Archive@1.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Serilog.Sinks.File.Archive&version=1.2.0
                    
Install as a Cake Addin
#tool nuget:?package=Serilog.Sinks.File.Archive&version=1.2.0
                    
Install as a Cake Tool

Serilog.Sinks.File.Archive

NuGet Build status

A FileLifecycleHooks-based plugin for the Serilog File Sink that works with rolling log files, archiving completed log files before they are deleted by Serilog's retention mechanism.

The following archive methods are supported:

  • Compress logs in the same directory (using GZip compression)
  • Copying logs to another directory
  • Compress logs (using GZip compression) and write them to another directory

Getting started

To get started, install the latest Serilog.Sinks.File.Archive package from NuGet:

Install-Package Serilog.Sinks.File.Archive

To enable archiving, use one of the new LoggerSinkConfiguration extensions that has a FileLifecycleHooks argument, and create a new ArchiveHooks. For example, to write GZip compressed logs to another directory (the directory will be created if it doesn't already exist):

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("my-app.log", hooks: new ArchiveHooks(CompressionLevel.Fastest, "C:\\My\\Archive\\Path"))
    .CreateLogger();

Or to copy logs as-is to another directory:

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("my-app.log", hooks: new ArchiveHooks(CompressionLevel.NoCompression, "C:\\My\\Archive\\Path"))
    .CreateLogger();

Or to write GZip compressed logs to the same directory the logs are written to:

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("my-app.log", hooks: new ArchiveHooks(CompressionLevel.Fastest))
    .CreateLogger();

Note that archival only works with rolling log files, as files are only deleted by Serilog's rolling file retention mechanism.

As is standard with Serilog, it's important to call Log.CloseAndFlush(); before your application ends.

Background Archiving

Archiving runs synchronously by default. To move compression and copying off the logging thread, opt in with archiveAsync: true:

var hooks = new ArchiveHooks(
    archiveAsync: true,
    compressionLevel: CompressionLevel.Fastest,
    targetDirectory: "C:\\My\\Archive\\Path");

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("my-app.log",
        rollOnFileSizeLimit: true,
        fileSizeLimitBytes: 10 * 1024 * 1024,
        retainedFileCountLimit: 2,
        hooks: hooks)
    .CreateLogger();

Log.Information("Hello from the application");

The hook synchronously renames each obsolete file to {originalPath}.{guid}.archive-pending in its source directory. The rename stays on the source filesystem even if the archive directory is on another volume. Archive filenames remain the same as in synchronous mode, and the pending source is deleted only after archiving succeeds.

Jobs run one at a time per hook instance, in queue order. The queue has no size limit: if archiving falls behind, pending files consume disk space until processed. Directory tokens are resolved when a file is queued. CompressionLevel.NoCompression also supports background copying, but its target must differ from the original path.

To limit the number of archived files, use the overload with retainedFileCountLimit:

new ArchiveHooks(retainedFileCountLimit: 10, archiveAsync: true,
    compressionLevel: CompressionLevel.Fastest, targetDirectory: "C:\\My\\Archive\\Path")

Archive retention runs after each successful archive. As with synchronous archiving, a target directory containing date tokens cannot be combined with an archive count limit.

Compression or copying writes directly to the final archive file. A lock shared by hook instances protects destination writes and retention so another job cannot overwrite or delete an archive while it is being written. Renaming source logs and deleting pending sources happen outside that archive lock. The .archive-pending sources are excluded from retention and remain available for manual recovery if archiving is interrupted.

Interrupted compression: Any aborted background compression leaves the uncompressed source file at its renamed {originalPath}.{guid}.archive-pending path for manual recovery, including when the application exits before compression finishes. Background jobs are not automatically awaited at shutdown. You can optionally call await hooks.BackgroundRunningArchiveTask() to wait for jobs queued before that call.

Failures and recovery: A failed rename is reported synchronously, allowing Serilog to retain the original file. Background failures are reported through Serilog's SelfLog and leave the pending source in place. BackgroundRunningArchiveTask() gives a task that waits for jobs to finish but does not propagate background archive failures. Pending sources are excluded from archive retention and are not retried automatically. Recover them manually using the original filename embedded in the pending filename. A failed archive may leave an incomplete destination, so use the retained source for recovery.

The original path no longer exists after a background archive is queued. If combining lifecycle hooks, run any hook that needs the source path before ArchiveHooks.

Token Replacement

The targetDirectory constructor parameter supports replacement of tokens at runtime.

Tokens take the form {Name:FormatString}, where Name is the name of a supported token, and FormatString defines how the token value should be formatted.

At present, 2 tokens are supported, UtcDate and Date. These use standard .NET date format strings to insert components of the current date/time into the path. For example, you may wish to organise archived files into folders based on the current year and month:

new ArchiveHooks(CompressionLevel.Fastest, "C:\\Archive\\{UtcDate:yyyy}\\{UtcDate:MM}")

JSON appsettings.json Configuration

It's also possible to enable archival when configuring Serilog from a configuration file using Serilog.Settings.Configuration. To do this, you will first need to create a public static class that can provide the configuration system with a configured instance of ArchiveHooks:

using Serilog.Sinks.File.Archive;

namespace MyApp.Logging
{
    public class SerilogHooks
    {
        public static ArchiveHooks MyArchiveHooks => new ArchiveHooks(CompressionLevel.Fastest, "C:\\My\\Archive\\Path");
    }
}

The hooks argument in Your appsettings.json file should be configured as follows:

{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "my-app.log",
          "fileSizeLimitBytes": 10485760,
          "rollOnFileSizeLimit": true,
          "retainedFileCountLimit": 5,
          "hooks": "MyApp.Logging.SerilogHooks::MyArchiveHooks, MyApp"
        }
      }
    ]
  }
}

To break this down a bit, what you are doing is specifying the fully qualified type name of the static class that provides your ArchiveHooks, using Serilog.Settings.Configuration's special :: syntax to point to the MyArchiveHooks member.

About FileLifecycleHooks

FileLifecycleHooks is a Serilog File Sink mechanism that allows hooking into log file lifecycle events, enabling scenarios such as wrapping the Serilog output stream in another stream, or capturing files before they are deleted by Serilog's retention mechanism.

Other available hooks include:

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 is compatible.  net463 was computed.  net47 was computed.  net471 is compatible.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on Serilog.Sinks.File.Archive:

Package Downloads
Shinya.Logging.Serilog.Sinks.File

Shinya.Framework

IceCoffee.AspNetCore

A simple AspNetCore web api library.

Nefarius.Utilities.AspNetCore

My opinionated collection of utilities for ASP.NET Core applications.

Xfrogcn.AspNetCore.Extensions

AspNetCore extensions library,includes function as logging, HTTP requests, authentication token management, parallel queue processing, and more

SerilogTester

This will help you to log messages inside temp folder

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Serilog.Sinks.File.Archive:

Repository Stars
GZTimeWalker/GZCTF
The GZ::CTF project, an open source CTF platform.
Version Downloads Last Updated
1.2.0 689 11/8/2026
1.1.0 12,091 10/15/2026
1.0.8 43,997 7/18/2026
1.0.6 1,010,246 9/10/2024
1.0.5 295,353 2/16/2024
1.0.4 45,090 12/20/2023
1.0.3 287,087 11/22/2022
1.0.2 135,713 7/26/2022
1.0.1 508,222 6/26/2020
1.0.0 5,264 4/29/2020