Perl Subroutine for Logging

I have a simple perl subroutine that I use often to create a log file for my scripts. This is not the best way to do logging but just a quick way to log.

#!/bin/perl
#############################################################
#
#############################################################
use Time::localtime;
$LOG_LOCATION="/var/log";
$LOG_FILE_PREFIX="myscript";
logMessage("This is a test");
#############################################################
# Returns logfile = /var/log/myscriptYYYYMMDD.log
#############################################################
sub getLogFilename()
{
my $currentYear;
my $currentMonth;
my $currentDay;
my $targetFilename;
my $currentDateStat;
$currentDateStat = localtime;
$currentYear  = $currentDateStat->year + 1900;
$currentMonth = $currentDateStat->mon + 1;
$currentDay   = $currentDateStat->mday;
$targetFilename = $LOG_LOCATION . "/" . $LOG_FILE_PREFIX;
$targetFilename .= sprintf "%02d", $currentYear;
$targetFilename .= sprintf "%02d", $currentMonth;
$targetFilename .= sprintf "%02d", $currentDay;
$targetFilename .= ".log";
return $targetFilename;
}
#############################################################
# Append the message to the log file with the current timestamp
#############################################################
sub logMessage()
{
my ($messageText) = (@_);
my $now = ctime();
my $logFilename = getLogFilename();
open(LOG_FILE, "< < $logFilename") || die("Unable to open log file $logFilename!");
print(LOG_FILE "$now: $messageText\n");
close(LOG_FILE);
}

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.