Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4J2 RollingFileAppender programatically

Tags:

java

log4j2

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

}

like image 941
Praveen Kumar Avatar asked Sep 28 '26 16:09

Praveen Kumar


1 Answers

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");
like image 172
Piotr P. Karwasz Avatar answered Oct 01 '26 22:10

Piotr P. Karwasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!