I'm trying to implement a custom handler that logs parsed LogRecord
objects into a file (basically what FileHandler
or StreamHandler
does). My currently implementation is shown below:
public final class ErrorHandler extends Handler {
private static final String OUTPUT_FILE = ".output";
private final Formatter formatter = new CustomFormatter();
private BufferedWriter writter;
@Override
public void publish(LogRecord record) {
if (record.getLevel() == SEVERE || record.getLevel() == WARNING) {
writeToOutput(record);
}
}
void writeToOutput(LogRecord log) {
try {
if (writter == null) {
writter = new BufferedWriter(new FileWriter(OUTPUT_FILE, true));
}
writter.write(formatter.format(log));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void flush() {
}
@Override
public void close() {
try {
writter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
P.S.: I known that we can achieve the same as the code above just by setting filter and formatter on a FileHandler
or StreamHandler
however I'll need the hookpoints later in the future.
My problem is, if I leave flush()
with no implementation, although output file gets created, no log is written there. If I call writter.flush()
inside flush()
, the log is duplicated. Any though why this might be happening?