Archive

Posts Tagged ‘Perl’

Perl: Unbuffered File Logging Module

August 21st, 2009 No comments

This an old Perl module I dug up which is quite a handy, there is no file write buffering so if you do a tail -f on the log file while it’s writing you can see real time what is going into the log file.


Logger Module

package Logger;
# Logger.pm
#---------------------------------------------------
#
# Basic module to log to file
#
#---------------------------------------------------
# Constructor for logger module

sub new{
    my $class = shift;
    my $args = shift;
    
    # Default is to create a new logfile, NOT to append to it
    my $append = 0;
    if (defined($args->{append})){
		$append = $args->{append};
    }

    my $disable = 0;
    if (defined($args->{disable})){
		$disable = $args->{disable};
    }
    
    my $self = { filename => $args->{filename},
		 		 append => $append,
		 		 line_no => 0,
		 		 disable => $disable
	     };
    
    bless($self,$class);
    $self->_init();
}

#---------------------------------------------------
# Initialise the log file

sub _init{
    my $self = shift;
    if (!$self->{disable}){
		$filename = $self->{filename};
	
		if ($self->{append}){
	    	# Open a file for appending in write mode 
	    	open(LOG,">> $filename");
	    	select LOG; 
	    	$| = 1;
	    	select STDOUT;
	    	$self->{log_handle} = *LOG;
		}
		else{
	    	# Create a new file in write mode
	    	open(LOG,"> $filename");
	    	select LOG; 
	    	$| = 1;
	    	select STDOUT;
	    	$self->{log_handle} = *LOG;
		}
    }
    
    return $self; 
}

#---------------------------------------------------
# Add to the log file

sub add{
    my $self = shift;
    if (!$self->{disable}){
		my $str = shift;
	
		my $handle = $self->{log_handle};
		my $timestamp = localtime(time);
		my $line_no = ++$self->{line_no};
		print $handle "[$timestamp#$line_no]: " . $str . "\n"; 
    }
}

#---------------------------------------------------
# Close log file

sub close{
    my $self = shift;
    if (!$self->{disable}){
		my $handle = $self->{log_handle};
		close($handle);
    }
}

#---------------------------------------------------
1;


Logger Module Usage

#!/usr/bin/perl -w

use strict;
use lib 'MyPerlLibDir/';
use Logger;

my $myLogString = 'This text will appear in the log file';

my $loggerObj = new Logger({ append => 0, disable => 0, filename => 'MyLogFile.txt'  });
$loggerObj->add($myLogString);
$loggerObj->close();