在线阅读文档后,我想尝试在本地计算机上测试 FileAppender。当我通过调用 build 方法创建对象时,我得到了错误。
我将在应用程序中升级 log4j 版本,并且当我无法在本地创建和测试一个文件附加程序时正在学习文件附加程序。我尝试在互联网上查找并找到一些有关如何创建它的代码。当我尝试相同时,我在堆栈跟踪中得到错误显示。我正在使用 Windows 机器并在 netbeans 上运行代码。
package logtest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.appender.FileAppender;
class Test
{
public void appendLogs(String logEvent)
{
LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
Configuration conf = ctx.getConfiguration();
FileAppender.Builder b = FileAppender.newBuilder();
b.withFileName("TestFile");
b.withAppend(true);
b.build();
FileAppender fa = b.build();
System.out.println(fa.toString());
fa.start();
fa.error("Error message");
}
}
public class LogTest {
private static final Logger LOG = LogManager.getLogger(LogTest.class);
public static void main(String[] args) {
Test t = new Test();
t.appendLogs("Test log");
System.out.println(t.toString());
t.appendLogs("This is an error in a file");
LOG.debug("This Will Be Printed On Debug");
LOG.info("This Will Be Printed On Info");
LOG.warn("This Will Be Printed On Warn");
LOG.error("This Will Be Printed On Error");
LOG.fatal("This Will Be Printed On Fatal");
LOG.info("Appending string: {}.", "Hello, World");
}
}
在调用 build() 方法期间出现错误。
Exception in thread "main" java.lang.NullPointerException: name
at java.util.Objects.requireNonNull(Objects.java:228)
at org.apache.logging.log4j.core.appender.AbstractAppender.<init>(AbstractAppender.java:205)
at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.<init>(AbstractOutputStreamAppender.java:120)
at org.apache.logging.log4j.core.appender.FileAppender.<init>(FileAppender.java:259)
at org.apache.logging.log4j.core.appender.FileAppender.<init>(FileAppender.java:42)
at org.apache.logging.log4j.core.appender.FileAppender$Builder.build(FileAppender.java:104)
at logtest.Test.appendLogs(LogTest.java:17)
at logtest.LogTest.main(LogTest.java:31)
Java Result: 1
我不明白为什么我得到空异常。