本文介紹了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");
這篇關于Log4J2程序化RollingFileAppender的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,