Java: How to make two loggers write in different files (Logger)

5.6k Views Asked by At

I have 2 loggers in the same class, set up like this:

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

try {  
    // This block configure the logger with handler and formatter  
    fh = new FileHandler("C:/temp/test/MyLogFile.log");  
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();  
    fh.setFormatter(formatter);  
    // the following statement is used to log any messages  
    logger.info("My first log");  
} catch (SecurityException e) {  
    e.printStackTrace();  
} catch (IOException e) {  
    e.printStackTrace();  
}  

The second logger is set up the same way, just as logger2 and fh2 and MyLogFile2.log.

My problem is that whenever any logger logs, both files are written into, even though I only call one logger e.g. logger2.log(Level.INFO, "msg2").

Why is that? Is it because both loggers are open at the same time? But I do not want to .close()/create them each time I use them. Any better solution?

1

There are 1 best solutions below

3
On BEST ANSWER

You have to set another name for the instance here :

Logger logger = Logger.getLogger("MyLog");

Logger logger2 = Logger.getLogger("MyLog2");

Cause Logger.getLogger("MyLog") return an instance of the logger with name "MyLog" or create it if not exist