import java.util.Iterator; import java.io.File; import com.taregon.logreader.LogRecord; import com.taregon.logreader.ExceptionRecord; import com.taregon.logreader.FrameRecord; import com.taregon.logreader.ParserEngine; import com.taregon.logreader.LogRecordFilter; import com.taregon.logreader.LogReaderException; import com.taregon.logreader.filters.*; import com.taregon.logreader.impl.ParserEngineImpl; /** Code example of the Logreader API * This example can be compiled from the logreader-base.jar archive */ public final class LogreaderExample { /** Creates a new instance of LogreaderExample */ public LogreaderExample () { initializeParserEngine(); //get the ParserEngine from its interface ParserEngine parserEngine = ParserEngine.Singleton.get(); LogRecordFilter[] filters = getFilters(); Iterator iterator = null; try { //get the Iterator that contains the LogRecord objects from the log files in //the users home directory iterator = parserEngine.iterator( new File( System.getProperty( "user.home" ) ), filters ); } /* This exception would be thrown if there was an IOException or parser exception * was thrown */ catch( LogReaderException lre ) { //do whatever you want throw new RuntimeException( lre ); } //read the Iterator while( iterator.hasNext() ) { LogRecord logRecord = (LogRecord) iterator.next(); //the LogRecord may or may not have an ExceptionRecord, it may be null ExceptionRecord exceptionRecord = logRecord.getException (); System.out.println( logRecord ); } } /** In the filters package are a set of LogRecordFilter * objects that can filter out specified LogRecord * objects inside of the iterator. You can also write * your own LogRecordFilters. */ private static LogRecordFilter[] getFilters() { //we will use an ExceptionFilter and a LevelFilter //will include only LogRecord objects with Exceptions ExceptionFilter eFilter = new ExceptionFilter( true ); //will only accept LogRecord logged with level INFO and above LevelFilter lFilter = new LevelFilter( "INFO", true ); return new LogRecordFilter[]{ eFilter, lFilter }; } /** Will initalize the ParserEngine with * its implementation. This method should be called only * once. */ private static void initializeParserEngine() { /* Set the implementation to the ParserEngine interface. * The ParserEngine interface follows the facade pattern. * * Once the implementation is set to the interface it can * be obtained by any class in the same classloader. * The interface can be set only once. */ ParserEngine.Singleton.set( new ParserEngineImpl() ); } }