---
title: "How do you periodically archive old log files based on size or date?"  
description: "How do you periodically archive old log files based on size or date?"  
author: "ICSM Computer"  
published: 2025-05-13  
updated: 2025-05-27  
canonical: https://www.mindstick.com/forum/161615/how-do-you-periodically-archive-old-log-files-based-on-size-or-date  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 2 minutes  

---

# How do you periodically archive old log files based on size or date?

How do you periodically [archive](https://answers.mindstick.com/qa/38543/name-the-founder-and-former-director-of-the-national-film-archive-of-india-nfai-pune-who-died-recently-at-the-age-of-82) old [log](https://www.mindstick.com/articles/126269/the-main-uses-of-log-cabins) [files based on size](https://www.mindstick.com/interview/34128/how-do-you-split-a-large-file-into-multiple-smaller-files-based-on-size) or [date](https://yourviews.mindstick.com/story/3869/propose-day-2024-exciting-date-ideas-for-you-and-your-partner)?

## Replies

### Reply by Anubhav Sharma

To **periodically archive old [log files](https://www.mindstick.com/interview/34182/compress-old-log-files-e-g-zip-after-7-days) based on [size](https://www.mindstick.com/forum/159799/how-can-you-manage-the-size-of-mdf-and-ldf-files) or date** in C#, the recommended approach is to use a **logging framework** like **Serilog**, **NLog**, or **log4net**, as they provide built-in mechanisms for log rotation and archiving.

Here’s how to achieve it with best practices:

## 1. Using Serilog (Recommended)

### Install via NuGet:

```plaintext
Install-Package Serilog
Install-Package Serilog.Sinks.File
```

### Configuration for Rolling and Archiving by Date or Size:

```cs
Log.Logger = new LoggerConfiguration()
    .WriteTo.File(
        path: "logs/log-.txt",
        rollingInterval: RollingInterval.Day,              // Rolls logs daily
        fileSizeLimitBytes: 10_000_000,                    // Rolls by size
        rollOnFileSizeLimit: true,
        retainedFileCountLimit: 30                         // Keep last 30 files
    )
    .CreateLogger();
```

- `rollingInterval`: Can be `Day`, `Hour`, `Minute`, etc.
- `retainedFileCountLimit`: Automatically deletes oldest files.
- Log files will be named like: `log-20250527.txt`, `log-20250528_001.txt`, etc.

## 2. Using NLog

### Install via NuGet:

```plaintext
Install-Package NLog
Install-Package NLog.Config
```

### NLog Configuration (in `NLog.config`):

```xml
<targets>
  <target name="logfile" xsi:type="File"
          fileName="logs/log-${shortdate}.log"
          archiveFileName="logs/archives/log.{#}.log"
          archiveEvery="Day"
          archiveNumbering="Rolling"
          maxArchiveFiles="30"
          archiveAboveSize="10485760" />
</targets>
<rules>
  <logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
```

- Archives logs daily or when the file size exceeds 10 MB.
- Automatically maintains 30 archive files.
- Creates files like `log-2025-05-27.log`, `log.1.log`, etc.

## 3. Manual Archiving (if not using a framework)

You can implement a custom background task to archive log files:

```cs
var logDir = "logs";
var archiveDir = Path.Combine(logDir, "archive");
Directory.CreateDirectory(archiveDir);

foreach (var file in Directory.GetFiles(logDir, "*.log"))
{
    var fileInfo = new FileInfo(file);

    // Archive if older than 7 days or larger than 10 MB
    if (fileInfo.CreationTime < DateTime.Now.AddDays(-7) || fileInfo.Length > 10_000_000)
    {
        var destFile = Path.Combine(archiveDir, Path.GetFileNameWithoutExtension(file) + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip");

        using (var archive = ZipFile.Open(destFile, ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile(file, Path.GetFileName(file));
        }

        File.Delete(file);
    }
}
```

Schedule this using a timer or a Windows scheduled task.

## Summary

| Method | Archive by | Auto Cleanup | Recommended |
| --- | --- | --- | --- |
| **Serilog** | Size, Date | Yes | ✔️ |
| **NLog** | Size, Date | Yes | ✔️ |
| Manual C# Code | Size, Date | With effort | Use only if frameworks are not allowed |


---

Original Source: https://www.mindstick.com/forum/161615/how-do-you-periodically-archive-old-log-files-based-on-size-or-date

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
