本文介绍了Log4J2程序化RollingFileAppender的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式实例化和使用log4J2 RollingFileAppender,但无法创建RollingFileAppender的实例,对Build()方法的调用返回一个空值,导致出现NullPointerException异常。知道遗失了什么吗?

public class DailyRollingFileAppender {

public static void main(String[] args) {

    String pattern = "%d [%t] %-5level: %msg%n%throwable";
    String fileLogName = "logs/rolling.log";
    String filePattern = "rolling-%d{MM-dd-yy}.log.gz";

    String hourly = "0 0 0/1 1/1 * ? *";
    String daily = "0 0 12 1/1 * ? *";

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();

    DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
            .withMax("7")
            .withMin("1")
            .withFileIndex("max")
            .withConfig(config)
            .withCompressionLevelStr(Deflater.NO_COMPRESSION + "")
            .build();

    PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern(pattern).build();

    RollingFileAppender.Builder builder = RollingFileAppender.newBuilder();
    builder.withFileName(fileLogName);
    builder.withFilePattern(filePattern);
    builder.withPolicy(CronTriggeringPolicy.createPolicy(config, Boolean.TRUE.toString(), daily));
    builder.withStrategy(strategy);
    builder.setLayout(layout);
    builder.setConfiguration(config);
    RollingFileAppender raf = builder.build();
    raf.start();
    config.addAppender(raf);
    ctx.updateLoggers();

    for (int i = 0; i < 100; i++) {
        raf.append(asLogEvent("This is a debug message: {}"+ i, Level.DEBUG));
    }
}

private static LogEvent asLogEvent(String message, Level level) {
    return new Log4jLogEvent.Builder().setLoggerName("fileLog").setMarker(null)
            .setLevel(level)
            .setMessage(new SimpleMessage(message)).setTimeMillis(System.currentTimeMillis()).build();
}

}

推荐答案

调试配置方法时,您应该从状态记录器中读取消息。更好的是,将其级别设置为DEBUG(您可以使用-Dlog4j2.debug=true)。

您忘记提供附加器的名称,因此null

builder.setName("your_name");

这篇关于Log4J2程序化RollingFileAppender的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 18:09