Logging different logs in different files. But all logs go in same file

1k Views Asked by At

I am using java.util.logging library for logging.

My code is as follows :

package com.test.vesrionControlSystem.services;

import java.io.IOException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class TestMain {

    public static void main(String[] args) throws IOException, InterruptedException {
        // TODO Auto-generated method stub

        Logger logger = Logger.getLogger(TestMain.class.getName());
        Logger logger1= Logger.getLogger(TestMain.class.getName());
        FileHandler fh = new FileHandler("D:\\Logs\\FirstLogs.%g.log", 10000, 20, true);
        FileHandler fh1 = new FileHandler("F:\\Logs\\SecondLogs.%g.log", 10000, 20, true);
        fh.setFormatter(new Formatter() {

          @Override
          public String format(LogRecord record) {
            return new Date(record.getMillis()) + " " + record.getLevel() + ": " + record.getMessage() + "\n";
          }
        });

        fh1.setFormatter(new Formatter() {

              @Override
              public String format(LogRecord record) {
                return new Date(record.getMillis()) + " " + record.getLevel() + ": " + record.getMessage() + "\n";
              }
        });

        logger.addHandler(fh);
        logger1.addHandler(fh1);

        while(true) {
            logger.info("printing info");
            Thread.sleep(100);
            logger1.warning("printing warning");
            Thread.sleep(100);
            logger.severe("Printing error");
            Thread.sleep(100);
        }   
    }
}

Here infos and severe messages should print in firstLogs.log file where as warning messages should be printed in secondsLogs.log file.

But I see all three messages (info, warning and severe) in both the files.

Please help me understand what I am missing here.

2

There are 2 best solutions below

0
On BEST ANSWER

Its similar to one I answered recently but it was for log4j. please check it out How create diferents log File with different content using log4 in java configuration

0
On

The main issue is that both logger and logger1 are the same name in your test code. Change the names:

    Logger logger = Logger.getLogger(TestMain.class.getName() + ".0");
    Logger logger1= Logger.getLogger(TestMain.class.getName() + ".1");

If you want to filter with in the same logger then see Logging handler usage