I created the below wrapper for a singleton logger class so that I can log exceptions from any file and/or class. My inspiration comes from here: Logging to one file from multiple java files
I’m new to java and this is my first use of attempting to log exceptions to a file. While the following code does work, I noticed a few quirks I wanted to ask whether or not they were “normal behavior” or whether a workaround exists.
(1) Once the log file is created and has been written to with exceptions, if I edit the log file (e.g. remove some lines of text) then the log file is never written again from that moment forward. The web server needs to restart the domain associated with the web application before the log file is written to again. Is this normal? Ideally, I would like to retain only relevant errors in the log file, and delete the irrelevant ones, without needing to restart the web application’s domain in the web server.
(2) If I delete the log file, then later an exception occurs in the java program(s), the log file does not get created again, and the exception is lost. Again, the web server needs to restart the domain associated with the web application before a new log file is created. Is this normal, or is there a workaround somehow by editing the below code? Ideally, I’d like to be able to delete the log file at any time and have the application create a new one.
Again, I’m new here so feel free to point out of the above intentions are bad design, etc.
——code follows——
Here’s the file: LoggerWrapper.java
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;
public class LoggerWrapper {
public static final Logger myLogger = Logger.getLogger("Test");
private static LoggerWrapper instance = null;
public static LoggerWrapper getInstance() {
if(instance == null) {
prepareLogger();
instance = new LoggerWrapper ();
}
return instance;
}
private static void prepareLogger() {
try {
FileHandler myFileHandler = new FileHandler("/path/to/myLogFile.log", true);
myFileHandler.setFormatter(new SimpleFormatter());
myLogger.addHandler(myFileHandler);
myLogger.setUseParentHandlers(false);
myLogger.setLevel(Level.ALL);
} catch (Exception e) {
...
}
}
}
To call the above code in a different file or class, issue these lines (for example):
LoggerWrapper loggerWrapper = LoggerWrapper.getInstance();
...
loggerWrapper.myLogger.log(Level.SEVERE, "some text here"+e.fillInStackTrace());
I’m assuming this is running on linux? When you open the file it’s pointing to a reference to that file. When you delete the file the reference is gone, but since you saved the reference in a static variable, your code is now holding a file handle that points to nothing. Instead you should do something like
Which will just copy nothing over the file without changing the actual inode that the file points to.