Reputation: 473
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.
Upvotes: 1
Views: 2424
Reputation: 19
Don't forget to close the file after your FileHandler has logged.
With the close method from FileHandler Class:
Upvotes: 0
Reputation: 639
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.
Upvotes: 2
Reputation: 29
I think the problem you are presenting here is actually a feature.
From https://docs.oracle.com/javase/8/docs/api/java/util/logging/FileHandler.html
For a rotating set of files, as each file reaches a given size limit, it is closed, rotated out, and a new file opened. Successively older files are named by adding "0", "1", "2", etc. into the base filename.
So, as I see it all you have to do is to change the limit size of your log file :)
Upvotes: 0