Reputation: 37
if (outcome == 1) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh = new FileHandler("C:\\Temp\\Dice_Roll_J\\Logs.txt", true);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.log(Level.INFO, "Outcome 1.");
}
if (outcome == 2) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh = new FileHandler("C:\\Temp\\Dice_Roll_J\\Logs.txt", true);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.log(Level.INFO, "Outcome 2");
}
This program is in a while loop, every time it goes onto an if statement and logs the info into the file, it does that. But the problem is that it also makes another file called Logs.txt.1 and if i roll it again, Logs.txt.2 and so on. It also makes files called Logs.txt.lck.
How do I fix this? Any help will be greatly appreciated
Upvotes: 0
Views: 416
Reputation: 37
Logger logger = Logger.getLogger("MyLog");
FileHandler fh = new FileHandler("C:\\Temp\\Dice_Roll_J\\Logs.txt", true);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
Move that out of each if statement outside of the loop so the only thing left is the logger.log(Level.INFO, "Outcome x");
in the if statements and after that put fh.close();
Upvotes: 0
Reputation: 789
You seem to use this constructor right, my only guess is that the previous handler is still in possession of the file so the new handler just creates a new file. Try to create only one handler outside of your loop and using it for your logging purpose.
Upvotes: 1