使用log4j2 v2.9

时间:2017-10-17 17:03:54

标签: java logging log4j2

我对版本为2.9的log4j2有疑问。 基本上我想做与此处描述的相同(log4j),仅使用2.9: Sample log4j v1.x

我需要一个可以在类中的任何方法中调用的记录器。这是从某个起始点递归收集所有后续日志。该集合应该能够在以后以任何形式读出。

Logger logger = LogManager.getLogger();
public void meth1(){
  StringWriter/ List/ String or whatever
  logger.add(Collector);
  logger.info("Start");
  this.meth2();
  this.meht3();
  logger.info("Stop");
  => do something with the collected logs
}
public void meht2(){
  logger.info("meth2: add Collection");
}
public void meth3(){
  logger.info("meth3: add Collection");
}
public void meht4(){
  logger.info("foo");
}

只要在表单中设置了结尾,就应该在集合中包含以下日志:

  • 开始
  • meth2:添加收藏
  • meth3:添加收藏
  • 停止

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

过了一会儿,我想出了以下解决方案,它适用于我使用Log4J 2.8。我在代码中添加了一些注释来解释必要的不同步骤。

请求具有相同名称的记录器(标有/* 1 */的行与存储配置一样重要(标有/* 2 */的行)。这意味着不能使用类名获取记录器,或MyClass.class.getName()应使用/*2*/

public class LoggingTest {

    public static void main(String[] args) {

        // define the logger, could also be static in class
        final String loggerName = "myCollectingLogger";
        Logger logger = LogManager.getLogger(loggerName); /* 1 */

        // the log message collector
        StringWriter writer = new StringWriter();

        // start adapting the logger configuration
        LoggerContext ctx = LoggerContext.getContext(false);
        Configuration config = ctx.getConfiguration();

        // create our appender
        PatternLayout layout = PatternLayout.newBuilder().withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n").build();
        WriterAppender writerAppender = WriterAppender.newBuilder().setName("writerAppender").setTarget(writer).setLayout(layout).build();

        // add the appender to a LoggerConfig
        AppenderRef ref = AppenderRef.createAppenderRef("writerAppender", null, null);
        AppenderRef[] refs = new AppenderRef[] { ref };
        LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "example", null, refs, null, config, null);
        loggerConfig.addAppender(writerAppender, null, null);

        // enable the LoggerConfig in the LoggerContext
        config.addLogger(loggerName, loggerConfig); /* 2 */
        ctx.updateLoggers();

        // use the logger:
        logger.info("Start");
        logger.warn("foo bar");
        logger.error("relax, it's just a test");
        logger.info("Stop");

        System.out.println("--- the collected log messages: ---");
        System.out.println(writer.toString());
    }
}

答案 1 :(得分:0)

谢谢,我已经根据我的需要进行了调整:

public static StringWriter createStringWriter(String classname){
    StringWriter stringWriter = new StringWriter();
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    PatternLayout layout = PatternLayout.newBuilder()
            .withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n").build();
    WriterAppender writerAppender = WriterAppender.newBuilder()
                                        .setName(classname + "writeLogger")
                                        .setTarget(stringWriter)
                                        .setLayout(layout)
                                        .build();
    writerAppender.start();
    config.addAppender(writerAppender);
    LoggerConfig loggerConfig = config.getLoggerConfig(classname);
    loggerConfig.addAppender(writerAppender, null, null);
    ctx.updateLoggers();
    return stringWriter;
}

public static void removeStringWriter(String classname){
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(classname);
    loggerConfig.removeAppender(classname + "writeLogger");
    ctx.updateLoggers();
}