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");
相关文章