package class4_1_Singleton_eventlogger; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Date; /** * A class that writes messages to a predetermined logfile. * @author hornick */ public class EventLogWriter { // the PrintWriter used to actually output to the log file private PrintWriter printer; private static EventLogWriter e = null; // /** * constructor for this EventLogWriter */ private EventLogWriter() { System.out.println("EventLogWriter constructor called"); File f = new File( "eventlog.txt" ); try { // catch exceptions thrown by PrintWriter's constructor locally // creates the file automatically if it does not exist printer = new PrintWriter( f ); // associate PrintWriter with a disk file } catch( FileNotFoundException e ) { // invalid path or filename, or Windows security issue System.out.println("printing failed: FileNotFoundException "+ e.getMessage() ); } } // Factory method public static EventLogWriter getInstance() { //todo: implement double-checked locking per the ppt slide if( e == null ) e = new EventLogWriter(); return e; } /** * write an event message to a predetermined logfile, including the date of the event * @param eventDescription the message to write to the file */ public synchronized void logEvent( String eventDescription ) { System.out.println("logEvent: " + eventDescription); // echo to the console too printer.println(new Date() + ": " + eventDescription ); printer.flush(); // forces output to be dumped to the file (flushes cache) } }