奇怪的log4j声明

时间:2015-07-31 12:22:16

标签: java eclipse logging log4j

我的旧项目有问题:日志文件没有附加到Eclipse的控制台视图中。而不是在log4j.xml或log4j.properties中声明log4j使用的属性,而是在java中定义记录器:

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;


public class GCLogger {
    private static GCLogger _self;
    private Logger logger;

    private static final String NAME_FILE = "fichierLog.log";

    public static GCLogger getInstance() {
        if (_self == null || _self.logger == null) {
            GCLogger logger = new GCLogger();
            logger.initLogger();
            _self = logger;
        }
        return _self;
    }

    public void error(String msg, Exception e) {
        if (logger != null) {
            logger.error(msg, e);
        }
    }

    public void debug(String msg) {
        if (logger != null) {
            logger.debug(msg);
        }
    }

    private void initLogger() {
        logger = Logger.getRootLogger();
        FileAppender fa = new FileAppender();
        PatternLayout monLayout = new PatternLayout("%d{DATE} - %5p %c{1} - %m%n");
        logger.removeAllAppenders();

        try {
            File repLogs = new File(GCConstants.GC_REPERTOIRE_LOGS);
            if (!repLogs.exists()) {
                repLogs.mkdir();
            }

            fa = new FileAppender(monLayout, GCConstants.GC_REPERTOIRE_LOGS + File.separator + NAME_FILE, true);
            fa.activateOptions();
            fa.setImmediateFlush(true);

            logger.addAppender(fa);
            logger.setLevel(Level.ALL);

        } catch(Exception e) {
            logger = null;
        }
    }
}

是否有一种在控制台视图中显示fichierLog.log的简单方法(使用eclipse配置)?

如果没有,那么它的最小变化是什么?

1 个答案:

答案 0 :(得分:1)

最小更改 - 添加控制台appender:

ConsoleAppender console = new ConsoleAppender(monLayout); // re-use the layout
logger.addAppender(console);

<&意见GT; 但是,如果您对代码库进行其他更改,我强烈建议您更改此代码以使用外部配置 - 这将使您在长期(可能很短)的期限内更轻松。< / opinion>