I have created my own logging class for handling writes to a ".log" file and want to print out any exceptions that are thrown outside my own "try-catch" statements or throw new calls. For example, if an image file in specified URL is not found, it throws a NullPointerExceptionat runtime, which is not handled by me, but by Java itself.
I want to log those runtime exceptions to my logfile, but it does not seem to write them (or perhaps recognise them)
Here is the code to my method that writes to a log file:
public void writeLog(String message, Throwable t) {
File logDirectory = FileHelper.createDirectory(FileHelper.workingDirectory, "logs");
File logFile = new File(logDirectory, this.logFileName);
if (!logFile.exists()) {
try {
boolean created = logFile.createNewFile();
if (!created) {
throw new IOException("Failed to create log file");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
try (FileWriter fw = new FileWriter(logFile, true)) {
if (!this.isSystemMessageWritten(logFile)) {
this.writeSystemMessage(fw);
}
fw.write(String.format("%s%n", message));
try (PrintWriter pw = new PrintWriter(fw)) {
t.printStackTrace(pw);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}