Archive

Posts Tagged ‘logging module’

Simple Java File Logging

September 30th, 2009 No comments

Not much to say about this one, a small one off independent class to simplify the process of logging stuff to file. Something like this is often handy when writing backgrounded daemon processes.

FileLogger class

package Utils;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileLogger{
	
	private File logFile;
	
	private long logEntryNo = 0;
	
	private static FileLogger instance = null;
	
	public static final String DEFAULT_LOG_FILEPATH = "bin/Log/Daemon.log";
	
	public FileLogger(String logFilePath){
		logFile = new File(logFilePath);
		try{
			logFile.createNewFile();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		calcNumLines();
		instance = this;
	}
	
	public FileLogger(File logFile){
		this.logFile = logFile;
		calcNumLines();
		instance = this;
	}
	
	public static FileLogger getInstance(){
		return instance;
	}

	/**
	 * Adds and entry in the log file but also echos the log to standard out
	 * 
	 * @param data
	 * @param printToStdOut
	 */
	
	public void add(String data,boolean printToStdOut){
		if (printToStdOut){
			System.out.print("\n" + data + "\n");
		}
		add(data);
	}
	
	/**
	 * Add a log file entry
	 * 
	 * @param data
	 */
	
	public synchronized void add(String data){
		DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
		Date date = new Date();
		String dateTime = dateFormat.format(date);
		
		try{
			if (logFile.createNewFile()){
				FileWriter fileWriter = new FileWriter(logFile);
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
				bufferedWriter.newLine();
				bufferedWriter.close();
			}
			else{
				FileWriter fileWriter = new FileWriter(logFile,true);
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
				bufferedWriter.newLine();
				bufferedWriter.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void calcNumEntries(){
		try {
			FileReader fileReader = new FileReader(logFile);
			BufferedReader bufferedFileReader = new BufferedReader(fileReader);
			
			try{
				String line;
				while((line = bufferedFileReader.readLine()) != null){
					Pattern p = Pattern.compile("^\\[\\d+\\.\\d+\\.\\d+\\s+\\d+:\\d+:\\d+]#\\d+");
					Matcher m = p.matcher(line);
					
					if (m.find()){
						logEntryNo++;
					}
				}
				bufferedFileReader.close();
			} 
			catch (IOException e){
				e.printStackTrace();
			}
		} 
		catch (FileNotFoundException e){
			// The log file hasn't been created yet so gracefully ignore that fact
		}
	}
	
}

Usage:

FileLogger myFileLogger = new FileLogger(FileLogger.DEFAULT_LOG_FILEPATH);
myFileLogger.add("my log entry");

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();