简体   繁体   中英

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

}

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM