Efficiency in code to cycle log file

D

Domenico Discepola

Hello. I wrote a subroutine that creates log file entries in a text file
using the following format: script name version date time status message. A
sample entry would be:

script v1.0.2 2004/07/12 12:29:18 (I): Message 1 here
script v1.0.2 2004/07/12 12:29:48 (I): Message 2 here
etc.

The important part is that the first 5 "fields" are space seperated whose
positions will not change. I now wanted to cycle the log file if the date
of the log file entry was greater than a certain value, based on today's
date. In other words, delete all log file entries older than X days. The
code I posted works well enough for me but it is not very elegant. Right
now, the script simply creates a "temporary" file with the log file entries
I want to keep, leaving the original file untouched. I would consider it a
learning experience if someone can provide me with some suggestions for
tightening the code.

Regards,

Domenico
###############

#!perl
use strict;
use warnings;
use diagnostics;
use Date::pcalc qw( Delta_Days );

our $g_file_log = "c:\\work\\jps.log";
our $g_file_log_tmp = "c:\\work\\jps.log.tmp";

sub cycle_log {

my ( $cycle ) = @_;

my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
localtime(time);
#Because year is 2 digits and month starts at 0
$year += 1900;
$mon += 1;

open(CFILE, "< ${g_file_log}") || die "Cannot open ${g_file_log} file\n";
while (<CFILE>) {

my @a = split / +/, $_;
my ( $iyyyy, $imm, $idd ) = split /\//, $a[2];
my $diff = Date::pcalc::Delta_Days( $iyyyy, $imm, $idd , $year, $mon,
$mday, );

if ( $diff >= $cycle ) {
#print "Will be deleted because > $cycle days: $iyyyy, $imm, $idd \n";
next;
} else {
open (my $file, ">>${g_file_log_tmp}") || return 2;

## code improvement part here ####
my $string;
foreach my $el ( @a ) {
chomp ( $el );
$string = $string . "${el} ";
}

$string =~ s/(^.+)(\s$)/$1/;
$string = $string . "\n";
print $file $string;
close $file;
###################################
}
}
close (CFILE) || die "Cannot close $g_file_log file\n";
}

sub main {
&cycle_log( 2 );
}
main();
exit 0;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top