使用 log4j2 以编程方式创建 FileAppender 时出错

Error in programmatically creating FileAppender using log4j2

我想在阅读在线文档后尝试在我的本地机器上测试 FileAppender。当我通过调用构建方法创建对象时出现错误。

我将在一个应用程序中升级 log4j 版本,当我无法创建和测试一个文件附加程序时,我正在学习文件附加程序 locally.I 尝试在互联网上查找并找到了一些关于如何创建它的代码。当我尝试相同的操作时,我在堆栈跟踪中得到如下所示的错误。我正在使用 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

我不明白为什么我得到空异常。

您需要为附加程序设置一个名称。

FileAppender.Builder b = FileAppender.newBuilder();
b.withFileName("TestFile");
b.withAppend(true);
b.setName("my-appender");
b.build();
FileAppender fa = b.build();