views:

29

answers:

2

I use java.util.logging, and I put the log inside a application managed bean, since I think there should be just one logger for the entire application.

@ManagedBean(name="logging")  
@ApplicationScoped
public class Logging {

    private static Logger logger = Logger.getLogger(Logger.class.getName());
    private static FileHandler fh = null;

    public Logging() {
        try{
            fh = new FileHandler("DMBackingBean");
        }catch(IOException ignore){}
        logger.addHandler(fh);
        logger.setLevel(Level.ALL);
    }

    public Logger getLogger(){
        return logger;
    }
}

Here is the strange behavior I run into. When I run the program the first time, I log AAA inside DMBackingBean. Then I redeploy the application (new session), now I saw another log file is created, DMBackingBean.1 with content of AAA. The contain of DMBackingBean is now
AAA
AAA

Two question: Is it standard to put the logging inside an application scoped bean? Is there a way for me to have all the logs append into one file, instead of every time I redeploy (new session), a new log file is created?

A: 

You need to undo your logging when the bean is undeployed. Otherwise you will add a new one everytime you redeploy.

Thorbjørn Ravn Andersen
how can I undo the log? can u be a bit more specific?
Harry Pham
You call "addHandler(...)". When that deployment goes away, you need to call the opposite method too. Consider it similar to close().
Thorbjørn Ravn Andersen
+2  A: 

Is it standard to put the logging inside an application scoped bean?

IMO, it's more typical to create a hierarchy of loggers so that you can activate and control logging in a fine grained manner (e.g. configuring com.acme.Foo to log at the ERROR level while configuring the logging of com.acme.bar.BAR at the DEBUG level).

Is there a way for me to have all the logs append into one file, instead of every time I redeploy (new session), a new log file is created?

It looks like you need to create an appending file handler:

try { 
    // Create an appending file handler
    boolean append = true; 
    FileHandler handler = new FileHandler("my.log", append); 
    ...
}

References

Pascal Thivent
I try `FileHandler handler = new FileHandler("my.log", true)`, but it still creating new log file every time I rerun the application. Any idea why?
Harry Pham