Praveen Kumar
Praveen Kumar

Reputation: 1539

Log4J2 RollingFileAppender programatically

I am working on instantiating and using log4J2 RollingFileAppender programmatically but unable to create an instance of a RollingFileAppender the call to build() method returns a null leading to a NullPointerException. Any idea on what is missing?

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();
}

}

Upvotes: 3

Views: 2837

Answers (1)

Piotr P. Karwasz
Piotr P. Karwasz

Reputation: 16185

While debugging your configuration method, you should read the messages from the status logger. Even better, set its level to DEBUG (you can use -Dlog4j2.debug=true).

You forgot to provide a name for your appender, hence the null:

builder.setName("your_name");

Upvotes: 3

Related Questions