0

#other code & randomizer

if(outcome == 1){
    Logger logger = Logger.getLogger("MyLog");
    FileHandler fh;
    fh = new FileHandler("C:\\Temp\\Dice_roll\\Logs.txt", true);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.log(Level.INFO, "Outcome 1.");
}

This is supposed to add more text into the txt file, which it does. BUT, it also makes another txt file called Log.txt.1 and then if I roll it again, Log.txt.2 and so on. How would I fix this?

Any help will be much appreciated.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35
MasterHackerLOIS
  • 39
  • 1
  • 1
  • 8

1 Answers1

1

You are adding a new FileHandler each time you try to log. It has to be done only once!

You have to separate your Logger setup and its use.

Note that your logger has to be declared as static final otherwise it could be garbage collected and you could have to set it up again.

Setup code

private static final Logger logger = Logger.getLogger("MyLog");
static {
    FileHandler fh;
    try {
        fh = new FileHandler("C:\\Temp\\Dice_roll\\Logs.txt", true);
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
    } catch (SecurityException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    logger.setLevel(Level.ALL);
}

Logging

if(outcome == 1){
    logger.log(Level.INFO, "Outcome 1.");
}

Note that if I were you, I would rather use a configuration file.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35
  • 2
    The logger has to be declared static final otherwise the FileHandler will get [garbage collected and the logger setting are lost](https://stackoverflow.com/questions/40923754/selenium-many-logs-how-to-remove/40934452#40934452). – jmehrens Jan 04 '18 at 22:21
  • @C.Champagne the line `fh = new FileHandler("C:\\Temp\\Dice_roll\\Logs.txt", true);` is an error, the error is: `unreported exception IOException; must be caught or declared to be thrown`. – MasterHackerLOIS Jan 05 '18 at 21:34
  • @MasterHackerLOIS it just means that you need to catch a possible exception. See my updated code. Note that I still advise you to use configuration instead. – C.Champagne Jan 08 '18 at 09:32
  • @MasterHackerLOIS By the way don't forget to create the directory where the log file is created if it doesn't exist yet ;) – C.Champagne Jan 08 '18 at 09:54