Simple Perl Logging Subroutine


In the course of programming perl I have often found it useful to have the ability to quickly write to a logfile. I wrote the subroutine below to assist in debugging my scripts.

my $logdir="/var/log/";
sub logit
{
    my $s = shift;
    my ($logsec,$logmin,$loghour,$logmday,$logmon,$logyear,$logwday,$logyday,$logisdst)=localtime(time);
    my $logtimestamp = sprintf("%4d-%02d-%02d %02d:%02d:%02d",$logyear+1900,$logmon+1,$logmday,$loghour,$logmin,$logsec);
    $logmon++;
    my $logfile="$logdir$logmon-$logmday-logfile.log";
    my $fh;
    open($fh, '>>', "$logfile") or die "$logfile: $!";
    print $fh "$logtimestamp $s\n";
    close($fh);
}

This subroutine makes writing to a logfile as simple as the following.

logit("Something somthing $variable");

Not the most complicated subroutine, but it certainly gets the job done. I think the coolest part of the whole script is probably splitting localtime into multiple variables and then using sprintf() to reassemble them into an appropriate timestamp.

About these ads

One thought on “Simple Perl Logging Subroutine

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s