Home > Software design >  Delete the log file after archiving using NLog C#
Delete the log file after archiving using NLog C#

Time:02-05

I want to archive log files periodically(for every hour) from "Logs" folder to "Archive" folder and then delete those archived files from "logs" folder immediately. Can we achieve this using NLog?

Currently, I am using the below c# code for archiving, but I am not seeing the desired output. We are using Nlog version 4.7.11.

target.FileName = @"C:\Logs\Log-${date:format=yyyy-MM-dd-hh}.log";
target.ArchiveFileName = @"C:\Archives\Log-${date:format=yyyy-MM-dd-hh}.log";
target.ArchiveEvery = FileArchivePeriod.Hour;
target.ArchiveOldFileOnStartup = true;
target.DeleteOldFileOnStartup = true;
target.MaxArchiveDays = 10;
target.ArchiveNumbering = ArchiveNumberingMode.Date;
target.MaxArchiveFiles = 50;
target.ArchiveDateFormat = "yyyy-mmm-dd hh-mm";
target.EnableArchiveFileCompression = true;

CodePudding user response:

You can extend your NLog method to run some method after logging. Please refer to the following: https://github.com/NLog/NLog/wiki/MethodCall-target.

MethodCall target: Calls the specified static method on each log message and passes contextual parameters to it.

You can create some code that uses System.IO to move and archive your code based on your needs.

CodePudding user response:

NLog supports 2 file-archive-modes:

  • Static FileName Archive-mode, where ArchiveEvery controls when to roll.
  • Dynamic FileName Archive-mode, where FileName contains ${date} or ${shortdate} (Rolls automatically)

NLog does not support mixing these 2 file-archive-modes. If you want files to be moved into the Archive-folder, then you must use static FileName:

target.FileName = @"C:\Logs\App.log";
target.ArchiveFileName = @"C:\Archives\App-{#}.log.zip";
target.ArchiveEvery = FileArchivePeriod.Hour;
target.ArchiveOldFileOnStartup = true;
target.DeleteOldFileOnStartup = true;
target.MaxArchiveDays = 10;
target.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
target.MaxArchiveFiles = 50;
target.ArchiveDateFormat = "yyyy-MM-dd-hh";
target.EnableArchiveFileCompression = true;

See also Do not mix dynamic with static-archive-mode

  • Related