Wednesday 24 February 2010

creating a log file

code snippet to create a module to open a log file for your perl script:


use Fcntl ':flock';
my $openlog = 0;
my $openlog_name="";

sub open_log
{
my $logfilename = $_[0];
$openlog = sysopen (LOGFILE, $logfilename, Fcntl::O_WRONLY|Fcntl::O_APPEND|Fcntl::O_CREAT, 0755);
select(LOGFILE); $| = 1; # make the output unbuffered. See the discussion of fork in the perlfunc man page.
select(STDOUT);
$openlog_name = $logfilename;
return $openlog;
}

sub log_message {
my($arg) = @_;
my $t = localtime;
# If the log file was successfully opened then log
if ($openlog) {
print LOGFILE "$$:${t}: $arg\n";
} else {
print "$$:${t}: $arg\n";
}
}

close(LOGFILE);

No comments:

Post a Comment

Tweets by @sriramperumalla