views:

60

answers:

1

Hi,

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!

+1  A: 

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;
        }
    }
});
Russ Hayward
I did a class myTextAppender extends AppenderSkeleton{ JTextArea area; //getters and setters of textarea}. When the gui initializes I do the myTextAppender a = new myTextAppender(); a.setArea(this.getTextArea());Logger.getRootLogger().addAppender(a); but I get log4j:ERROR Could not find value for key log4j.appender.WINDOW in the log4j. What am I doing wrong?
@Russ: I removed the log4J configuration file and it works. Is there a way to append only the logging messages of INFO and not WARNING?
Yes this should work: yourTextAreaAppender.setThreshold(Level.INFO);
Russ Hayward
@Russ: I tried it. I prints all messages of INFO level and higher. Is there a way to append only the INFO messages (not WARN or ERROR level as well)?
Yes use a filter - I have added it to the question to enable syntax highlighting.
Russ Hayward
@Russ: Thank you very much for your help!!!