Search code examples
javaloggingfilehandler

Can multiple loggers use the same handler?


Is it a good idea to use the same file handler in several loggers? I use the Java logging framework and I want different loggers to write into the same log file, but I don't know if this code example below is a good programming style.

import java.io.*;
import java.util.logging.*;

public class Alpha {
    private static final Logger LOGGER = Logger.getLogger(Alpha.class.getName());
    private static FileHandler loggingHandler;

    static {
        try {
            loggingHandler = new FileHandler("logfile.log", true);
            LOGGER.addHandler(loggingHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static FileHandler getLoggingHandler() {
        return loggingHandler;
    }
}

class Beta {
    private static final Logger LOGGER = Logger.getLogger(Beta.class.getName());

    static {
        LOGGER.addHandler(Alpha.getLoggingHandler());
    }
}

Solution

  • The Answer is yes.You can achieve this(for example) by making a singleton log class so any other class or thread tries creating a copy of it, will actually be using the same instance.

    Example implementation with java.util.logging:

    public class LogMe {        
        private static LogMe logMe;
        private static Logger logger;    
        private static FileHandler fh;
        private static Formatter sf;
    
        public LogMe() {
        //Make this class a singleton
            if (logMe != null) {
               return;
           }
    
            //Create the log file            
            try {
            fh = new FileHandler("../xyz/LogFile.log");
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        sf = new SimpleFormatter();
        fh.setFormatter(sf);            
        logger.addHandler(fh);
    
        //Part of making this class a singleton
        logger = Logger.getLogger("LogMe");
        logMe = this;        
    }
    
    public Logger getLogger() {
        return LogMe.logger;
    }
    }
    

    Then in your classes you will be using it like this:

     class MyClass1 {
        LogMe logMe1 = new LogMe();
        Logger logger2 = logMe1.getLogger();
        logger.info("X 01");
    }