Jatin
Jatin

Reputation: 31724

Logger not functioning properly

I am using java.util.logging.Logger Class for logging in my application. I have added FileHandler so that the application log is stored directly in log.txt file.

But for some reason, after the application is terminated the log is far from complete. On cmd, I can see all the statements but they are never appended to the file.

I have set FileHandler to the Logger by:

private void setLogger() {
    try {
        FileHandler hand = new FileHandler("log/log.txt", true);
        hand.setFormatter(new SimpleFormatter());
        Logger log = Logger.getLogger(ImageRename.MAIN_LOG);
        //log.setUseParentHandlers(false);
        log.addHandler(hand);
        log.setLevel(Level.ALL);          
    } catch (IOException e) {
        System.out.println("Could Not set logger");
    }
}

Any problem with flushing? How to solve it? Thanks.

PS: On debugging, I have noticed that in between

Logger.getLogger(ImageRename.MAIN_LOG).getHandlers().length

returns 0. Where as it should return 1. Initially it was printing 1, but somewhere down the line it becomes zero.

Upvotes: 1

Views: 821

Answers (2)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

The problem is ... garbage collection.

What is happening is likely the following:

  1. You call Logger.getLogger(ImageRename.MAIN_LOG);
  2. You setup the logger.
  3. Java notices it is unreferenced, and discards it.
  4. You call Logger.getLogger(ImageRename.MAIN_LOG); and expect to get the same logger.
  5. A fresh logger is set up with default configuration.

You can avoid this by two measures:

  • Use a configuration file logging.properties for configuration. When creating the logger, the Java logging API will consult the configuration, and thus recreate it appropriately.
  • Use static references. This is a best practise anyway. Equip each class with a logger:

    private final static Logger LOG =
        Logger.getLogger(ExampleClass.class.getName());
    

While the class is loaded it then should not be garbage collected AFAICT.

Upvotes: 3

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

See e.g. http://www.massapi.com/class/fi/FileHandler.html for an example (found via Google)

Note the following line, which may be your problem:

fileHandler.setLevel(Level.ALL);

(Note: this is the level of the Handler, not of the Logger or message.)

For debugging, first try to get messages at an ERROR level logged. Messages at level INFO and below are often supressed by default.

Also try setting the logging level as soon as possible. In my experience, the most reliable way of configuring Java logging is by using a properties file, and invoking Java with:

-Djava.util.logging.config.file=path/to/file/logging.properties

The reason is that the settings you do sometimes are not applied to loggers created before you loaded the settings, once some changes have been made to the logging.

Upvotes: 1

Related Questions