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?
You have to set another name for the instance here :
Cause
Logger.getLogger("MyLog")
return an instance of the logger with name "MyLog" or create it if not exist