开发者

Need to close additional FileHandler for JUL?

开发者 https://www.devze.com 2023-03-05 13:14 出处:网络
I\'m using java util logging for logging in a small Java EE application. To a开发者_运维技巧dd an additional FileHandler (for example for errors/warnings), I created a LoggerFactory that creates the a

I'm using java util logging for logging in a small Java EE application. To a开发者_运维技巧dd an additional FileHandler (for example for errors/warnings), I created a LoggerFactory that creates the actual logger and that statically add a filehandler to the "main" logger.

package de.il.myapp.logging;

public class LoggerFactory {

    private static final java.util.logging.Logger MAIN_LOGGER = java.util.logging.Logger.getLogger("de.il.myapp");

    static {
            try {
                final java.util.logging.FileHandler fh = new java.util.logging.FileHandler("error.log", 1024*1024, 5, true);
                fh.setLevel(Level.WARNING);

                final java.util.logging.Formatter formatterTxt = new java.util.logging.SimpleFormatter();
                fh.setFormatter(formatterTxt);
                MAIN_LOGGER.addHandler(fh);

            } catch (final IOException e) {
                //...
            }
        }
    }

    public static final Logger getLogger(final Class<?> clazz){
        return java.util.logging.Logger.getLogger(clazz);
    }
}

Everything works fine, except, when I stop the application, the lck file are still there. On a start, a new lck is created. So after some restarts the directory looks like this.

  error.log.0
  error.log.0.1
  error.log.0.1.lck
  error.log.0.2
  error.log.0.2.lck
  error.log.0.3
  error.log.0.3.lck
  error.log.0.lck

The question is: How can I avoid this? Do I have to close the filehandler at the end? But where? Since this is a Java EE application I don't you an exit point, do I? And why do I get ..log.0.X for the logfiles, not just ..log.0?

Thanks, Ingo


In Glassfish, you can use Lifecycle Listeners. In JBoss, you can use StartupServiceMBean. What app server are you using?


First of all you are not allowed to use java.io classes in EJBs:

Section 21.2.2 of the spec:

An enterprise bean must not use the java.io package to attempt to access files and directo- ries in the file system.

This means that you also should not use classes that in turn use java.io classes unless you obtain them by asking the container.

However if you create an eagerly loaded singleton session bean and perform the cleanup on @PreDestroy:

@Startup 
@Singleton 
public class FileHandlerCloser {

 @PreDestroy
 public void closeFileHandlers() {
  // close file handlers
 }

}

The spec is not very clear about this but I think singleton beans are destroyed after all other beans.

0

精彩评论

暂无评论...
验证码 换一张
取 消