开发者

log4j redirection to desktop application in swing

I have a GUI application开发者_如何学Python 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!


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;
        }
    }
});


Well this could be pretty simple,

  1. Specify the property in log4j.property file, in my case it is:

    log4j.rootLogger=S
    log4j.appender.S=com.ibm.nzna.projects.qit.gui.StatusMessageAppender
    log4j.appender.S.layout=org.apache.log4j.PatternLayout
    log4j.appender.S.layout.ConversionPattern=%m
    
  2. Write is new class with the following code :

    import org.apache.log4j.AppenderSkeleton;
    import org.apache.log4j.Level;
    import org.apache.log4j.spi.LoggingEvent;
    
    /**
     * @author Ashish Tyagi
     *
     */
    public class StatusMessageAppender extends AppenderSkeleton {
        private StatusBar statusBar = AppDefaultWin.getStatusBar();
        protected void append(LoggingEvent event) {
            if(event.getLevel().equals(Level.INFO)){
                    //here set the text of your swing component;
                   //in my case it is: statusBar.st_STATUS.setText(event.getMessage().toString());
            }
        }
    
        public void close() {
    
        }
        public boolean requiresLayout() {
            return false;
        }
    
    }
    
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜