2

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?

sandboxj
  • 1,234
  • 3
  • 21
  • 47

1 Answers1

2

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

Xephi
  • 431
  • 2
  • 9
  • By the way, it's more conventional to name the logger with the class or package : `Logger log = Logger.getLogger(this.getClass());` – Xephi Dec 18 '16 at 20:32
  • Thanks, I didnt know that part mattered as it just looked like a name. Is there a naming convention for a second logger in the same package? `Logger.getLogger(this.getClass().getName() + "2");` ? – sandboxj Dec 18 '16 at 20:34
  • Since it is not conventional to have 2 logger in the same class, not at all :p – Xephi Dec 18 '16 at 20:36