log4j redirection to desktop application in swing

Cratylus picture Cratylus · Sep 10, 2010 · Viewed 8.8k times · Source

I have a GUI application in swing, implemented in NetBeans. For the various functionality provided from the input of the user, a jar is used, which uses log4j for logging. All is ok, but I have to redirect information from log4j to a text area in my GUI. I have found that to redirect from log4j to swing text area, one must extend an AppenderSkeleton. My problem is that I can not modify the gui (so as to have a JTextArea that extends an AppenderSkeleton for example) so I have to have such a class that appends to my JTextarea. Now my application initializes before log4j. My problem is that I can not find a way to set as property to the AppenderSkeleton custom class, a reference to the jtextarea of my gui , so that when log4j initializes the appender, it will pass a reference to the application's text area. I tried in the log4J configuration file something like: log4j.appender.myAppender.theTextArea=path.to.myFrameclass.theTextArea hopping that log4j would call the setter in my appender and the getter from my frame to set the text area, but it does not work. How can I make the appender initialized by log4j, redirect info to my application? Or is there a way for my application to initialize the custom appender and notify log4j to use it for logging? Thank you!

Answer

Russ Hayward picture Russ Hayward · Sep 10, 2010

The simplest option is to programmatically add your appender once your GUI has been initialised. Something like this:

Logger.getRootLogger().addAppender(yourTextAreaAppender);

EDIT: To only log the INFO level do this:

yourTextAreaAppender.addFilter(new Filter() {
    @Override
    public int decide(LoggingEvent event) {
        if (event.getLevel().equals(Level.INFO)) {
            return ACCEPT;
        } else {
            return DENY;
        }
    }
});