why just when i add log to the try block, i can see it at the output file?

26 views Asked by At

i tried to provide an logger file output and i saw that only one line is showed at the output file - only the one that inside the try catch block, the others are just at the console

attached here my code for test

public class Something {

Logger logger = Logger.getLogger("");
FileHandler fh;

@BeforeEach
public void wallad() {
    System.out.println("hello");
}

@AfterEach
public void asddf() {
    System.out.println("pizza");
}

@Tag("test")
@Test
public void some() {

    try {
        fh = new FileHandler("C:\\MyLogFile.txt");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter);
        logger.log(Level.SEVERE, "severe");------->only these  
                     will show at the output file
        } 
        catch (Exception e) {
        e.printStackTrace();
        }

    logger = Logger.getLogger(Logger.class.getName());
    logger.setLevel(Level.FINEST);
    ConsoleHandler handler = new ConsoleHandler();
        handler.setLevel(Level.ALL);
        logger.addHandler(handler);
        logger.setUseParentHandlers(false);

    System.out.println("test1");
    logger.log(Level.WARNING, "warning");
    System.out.println("test2");
    logger.log(Level.INFO, "information");
    System.out.println("test3");
    logger.log(Level.SEVERE, "severe");
    System.out.println("test4");

    logger.log(Level.FINEST, "finest");
    System.out.println("test5");
    logger.log(Level.FINE, "fine");
    System.out.println("test6");
    logger.log(Level.FINER, "finer");
    System.out.println("test7");
    logger.log(Level.FINEST, "finest");

}
}

how can i take out all the log file? there is no way that it need to be inside the try catch block

2

There are 2 answers

9
Mark On BEST ANSWER

You're creating a new ConsoleHandler with ConsoleHandler handler = new ConsoleHandler(); which is good. You're also calling logger.addHandler(handler) which will add this ConsoleHandler to the logger.

This would also have a FileHandler if it were not for the fact that you just reinstantiated the logger variable with:

logger = Logger.getLogger(Logger.class.getName());

Simply remove this line and your logger will both have a FileHandler and ConsoleHandler.

1
Lho Ben On

By setting the handler to be ConsoleHandler, you no longer write to file,

ConsoleHandler handler = new ConsoleHandler();

Delete this line to continue writing to your file

logger = Logger.getLogger(Logger.class.getName());