Log4J2 RollingFileAppender 以编程方式

Log4J2 RollingFileAppender programatically

我正在以编程方式实例化和使用 log4J2 RollingFileAppender,但无法创建 RollingFileAppender 的实例,调用 build() 方法 returns 一个 null 导致 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");