I am interested to know if the Observer Pattern is correct approach for implementing code to monitor log files and their changes?
I am currently using it, but there seems to be an anomaly that I can't quite explain. Basically, i create a Class called FileMonitor that has a timer that fires, that iterates a list of unique files looking for a changed "lastmodified date".
Upon finding it, a list of Listeners are iterated through to find the matching file, and it's
fileChanged event is notified. It then begins to process the lines that were added in the file.
So to make my question more succinct:
If you do not want to use Java 7, you can get the same behavior with Apache IO.
From the official documentation:
FileAlterationObserver represents the state of files below a root directory, checking the filesystem and notifying listeners of create, change or delete events.
Here is how you can add listeners to define operations to be executed when such events happen.
File directory = new File(new File("."), "src"); FileAlterationObserver observer = new FileAlterationObserver(directory); observer.addListener(...); observer.addListener(...);
You will have to register the oberver(s) with a
FileAlterationMonitor. Continuing from the same documentation:
long interval = ... FileAlterationMonitor monitor = new FileAlterationMonitor(interval); monitor.addObserver(observer); monitor.start(); ... monitor.stop();
interval is the amount of time (in miliseconds) to wait between checks of the file system.
Look for package named
org.apache.commons.io.monitor in the library.