sysadmin intermediate

How to rotate and compress log files

Question

How do I implement a simple log rotation script in Perl that compresses old logs?

Use file operations and gzip compression:

#!/usr/bin/perl
use strict;
use warnings;
use File::Copy;
use IO::Compress::Gzip qw(gzip $GzipError);

my $logfile = '/var/log/myapp.log';
my $rotated = "/var/log/myapp.log." . time();

if (-f $logfile && -s $logfile > 10_000_000) {
    move($logfile, $rotated) or die "Move failed: $!";
    
    gzip $rotated => "$rotated.gz" or die "Gzip failed: $GzipError";
    unlink $rotated;
    
    open my $fh, '>', $logfile or die "Cannot create new log: $!";
    close $fh;
    
    print "Rotated and compressed log to $rotated.gz\n";
}

This script checks if the log exceeds 10MB, rotates it with a timestamp, compresses it with gzip, and creates a fresh log file.

Was this helpful?

Related Questions