开发者

log4j ContentAppender null when static

When ConsoleAppender is static, I get the following error from log4j:

log4j:ERROR Attempted to append to closed appender named [null].

Example code:

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
public class Logging {
    priva开发者_如何学Pythonte static final PatternLayout layout = new PatternLayout("[%d{dd MMM yyyy HH:mm:ss}] [%t] %-6r %-5p %m\n");
    private static final ConsoleAppender consoleAppender = new ConsoleAppender(layout);
    private Logger logger;
    private String filterClass;
    private boolean logFlag = false;

    public LoggingExample(Class c) {
        logger = Logger.getLogger(c);
        logger.setAdditivity(false);
        logger.removeAllAppenders();
        logger.addAppender(consoleAppender);
        consoleAppender.activateOptions();
        filterClass = c.getName();
    }

    public log() {
        logger.info("this doesn't work when ConsoleAppender is static!");
    }
}


That happens because removeAllAppenders() removes and closes all the appenders and the underlying writers. Your console appender's writer is then also closed when you do it because a console appender is already attached to the logger by default if you ever create more than one instance of LoggingExample.


I believe it has something to with the initialization of layout or consoleAppender. How do you know if layout or consoleAppender failed to construct?

I will use Static Initialization Block to do whatever logic is necessary to make sure the static objects get created:

    public class Logging {
        private static final PatternLayout layout;
        private static final ConsoleAppender consoleAppender;

        static { /* code to initialize layout and consoloAppender  */}
        // Rest of your code
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜