I have three classes and I want to add the logs to a shared single file. So the constructor of each class has a
fh = new FileHandler("log.txt", true);
LOGGER_A.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
}
catch (IOException ex) {
}
fh = new FileHandler("log.txt", true);
LOGGER_B.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
}
catch (IOException ex) {
}
When I run the second constructor it creates a new file called "log.txt.1". How to avoid this, I want to use the log.txt file for all classes.
Add the same FileHandler object to both of your loggers.
FileHandler will try to get a lock on the filename so no other FileHandlers can use the same file. If the FileHandler is unable to get the lock, it appends increasing numbers to the end of the filename until it gets a unique lock on the file. Since your first FileHandler already has the lock on log.txt, the second FileHandler cannot get the same lock.