Delete Log Files That Are Older Than 6 Months

Delete log files that are older than 6 months, how to delete log files, nlog delete old logs, how to delete log file, log4net delete old logs, nlog delete old logs

I'm using NLog in most of the web applications that I built. This library generates files with extension ".log" where the exceptions and tracing logs are stored. 

After, few months to years, I noticed that few applications reached a large number of log files generated over the time and this is totally normal especially if we are tracing major events in the application.

The files are consuming some good space of the hard disk. Therefore, there is a need to delete old files and cleanup the hard disk. To achieve this target without manual intervention, I developed a simple .NET console application and scheduled it to run periodically using 'Windows Task Scheduler'.

How to Delete Log Files using C#

The following C# code will delete all *.log files from a specific directory based on the creation date/time of the file, in my case I stored the folder path in the app.config this is the path where the log files are created and I'm deleting all files older than 6 months.

var files = new DirectoryInfo(ConfigurationManager.AppSettings["WebLogs"].ToString()).GetFiles("*.log");
foreach (var file in files)
{
   if (file.CreationTimeUtc < DateTime.Now.AddMonths(-6))
   {
      File.Delete(file.FullName);
   }
}

You can download the full source code from this link

How to Delete Log Files using PowerShell Script

Here is another way to cleanup the logs using PowerShell script:

# Get today's date
$Today = Get-Date

#Configure number of days to keep log files
$Days = "180"
$InspectionDay = $Today.AddDays(-$Days)

#Configure the path of log files to inspect
$LogFolder = "C:\inetpub\wwwroot\YourWebApplication\Logs"

#Define the log extension
$LogExt = "*.txt"

#Get Files
$Old_Files = Get-Childitem $LogFolder -Include $LogExt -Recurse | Where { $_.LastWriteTime -le "$InspectionDay" }

#Deleting those files
foreach ($File in $Old_Files){
  if ($File -ne $NULL) {
     Write-Host "File found , we are deleting File $File" -ForegroundColor "Yellow"
     Remove-Item $File.FullName -Recurse | out-null
   }
  else {
     Write-Host "Script Ends" -foregroundcolor "Green"
   }
}
Write-Host "Process Completed."  -foregroundcolor "Green"

Post a Comment

Previous Post Next Post