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);
    my $logfile="$logdir$logmon-$logmday-logfile.log";
    my $fh;
    open($fh, '>>', "$logfile") or die "$logfile: $!";
    print $fh "$logtimestamp $s\n";

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.


I passed the Real Estate Salesperson license test!

One more thing to check off the list. After taking the required coursework, which interestingly enough is self paced, and spending 5 frantic hours studying I have passed the test. I am pretty excited about this development because it should provide some additional income and give me additional material for this site.