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.


4 thoughts on “Simple Perl Logging Subroutine

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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