May 15, 2012

Delete logs older than 7 days

#! /usr/bin/perl

use strict;
use warnings;
#use CGI;
#use CGI::Carp qw(fatalsToBrowser);   
use Data::Dumper;

foreach my $file (</test/logs/log_*.txt>) {   
    if ( -M $file > 7 ) {
        print "\n Deleting the log file more than 7 days old: " . $file;
        unlink $file; #or die "\nFailed to remove $file: $!";
    }
}

print "\n\n";


1;


Note:
  • The above program is based on the time stamp of the files. 
  • The program detects files staring with 'log_' format and deletes these files whose time stamp of the file is greater than 7 days (since the current time stamp).
  • '-M' is used to check the timestamp
  • 'ulink' is used to remove file 
  • Please change the corresponding shebang line  (#! /usr/bin/perl) if you are using windows environment to test this perl script
  • In the above example, in the specified path (/test/logs/) I have some files like... Let us assume we have files like this 
log_1.txt (7 days old)
log_2.txt (8 days old)
log_3.txt (9 days old)
log_4.txt (10 days old)
log_5.txt (3 days old)
log_6.txt (4 days old)
error_log.txt (10 days old)
server_log.txt (10 days old)

Program Output: The program will delete files
log_1.txt, log_2.txt, log_3.txt, log_4.txt

Since the files 'error_log.txt' and 'server_log.txt' won't start with 'log_' the program don't delete them irrespective of the timestamp.


No comments:

Post a Comment