-
Notifications
You must be signed in to change notification settings - Fork 2
/
rotate_log.pl
64 lines (48 loc) · 1.17 KB
/
rotate_log.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/perl -w
use strict;
use File::Copy;
use File::Basename;
use File::Spec;
my $file = File::Spec->rel2abs( shift );
my $count = shift;
if ( ! -e $file )
{
exit;
}
my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime();
my $timestamp = sprintf( "%04d%02d%02d%02d%02d%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec );
if ( !copy( $file, "$file.$timestamp" ) )
{
print "ERROR: Could not copy '$file' to '$file.$timestamp': $!\n";
exit;
}
if ( !unlink( $file ) )
{
print "ERROR: Could not unlink '$file': $!\n";
exit;
}
print "'$file' -> '$file.$timestamp'\n";
if ( defined( $count ) )
{
my $filename = basename( $file );
my $directory = dirname( $file );
if ( !opendir( DIR, $directory ) )
{
print "ERROR: Could not open '$directory' for read: $!\n";
exit;
}
my @files = readdir( DIR );
closedir( DIR );
chomp( @files );
@files = grep { /^$filename/ } @files;
@files = sort( @files );
while( scalar( @files ) > $count )
{
my $oldFile = shift( @files );
print "Removing old file: $oldFile\n";
if ( !unlink( $oldFile ) )
{
print "ERROR: Could not unlink '$oldFile' during cleanup: $!\n";
}
}
}