Search code examples
javajava.util.loggingfilehandler

Java Logger wont log into file


I can't make my logger to work. Inside my code I have these lines :

private static final Logger log = Logger.getLogger(ServerThread.class.getName());
log.setUseParentHandlers(false);
FileHandler fh = new FileHandler("ex.txt", true);
SimpleFormatter sf = new SimpleFormatter();
fh.setFormatter(sf);
log.addHandler(fh);
log.setLevel(Level.FINE);

And later when I get input from user :

log.log(Level.FINE,inputString);

But all that happens is that fileHandler creates a file ex.txt, but nothing is logged into the file. I am sure that log.log() is being executed.


Solution

  • Make sure that you only create one FileHandler and ensure that your adjust the level of your FileHandler too.

    private static final Logger log = Logger.getLogger(ServerThread.class.getName());
    private static final FileHandler fh;
    static {
        try {
            log.setUseParentHandlers(false);
            fh = new FileHandler("ex.txt", true);
            fh.setFormatter(new SimpleFormatter());
            fh.setLevel(Level.FINE);
            log.addHandler(fh);
            log.setLevel(Level.FINE);
        } catch (IOException ioe) {
            throw new ExceptionInInitializerError(ioe);
        }
    }
    

    If you still don't see results then you should print the logger tree to ensure that the filehander and the loggers are created in the layout you are expecting.

    In general, you should should setup a logging.properties file.