#/usr/bin/perl use strict; my $dir = "/var/log"; # Location of the Log file my $logfile = "log.txt"; # Name of the Log file my $maxsize = 2_000_000; # Max size before rotating my $maxlogs = 10; # Number of rotates before archive my $archivetotal = 5; # Number of logs to archive my ($s, $m, $h, $dayOfMonth, $month, # Create date from + local time $yearOffset, $dow, $doy, $dst) = localtime(); my $year = 1900 + $yearOffset; my $date = $year * 1000 + ($month + 1) * 100 + $dayOfMonth; # Forma +t Date my $tarme; # Store names of files to be archived ### Switch to directory where log file is located chdir $dir; ### Check Size of log if(-s $logfile > $maxsize) { ### Rotate old logs for(my $i = $maxlogs - 1;$i > 0;$i--) { if(-e "${logfile}.$i") { my $j = $i + 1; rename "${logfile}.$i", "${logfile}.$j"; } } rename "$logfile", "${logfile}.1"; `echo "" >> $logfile`; ### Archive logs if(-e "${logfile}.$maxlogs") { for(my $i = $maxlogs - ($archivetotal - 1), my $j = 1;$i <= $m +axlogs;$i++, $j++) { rename "${logfile}.$i", "${logfile}.${date}.$j"; $tarme .= "${logfile}.${date}.$j "; } my $i = 1; my $tarfile = "${logfile}.${date}.tar"; while ( (-e $tarfile) || (-e "${tarfile}.gz") ) { $tarfile = "${logfile}.${date}.tar.$i"; $i++; } `tar -czf $tarfile $tarme`; `rm $tarme`; `gzip $tarfile`; } } else { print "Log file too small to rotate.\n\n"; }

In reply to Log Rotation by Danikar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.