log4j JsonLayout停止使用其他字段

goqiplq2  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(175)

我试图添加一些额外的字段,但JsonLayout似乎失败了。我是新的java,不能找到我错过了什么...

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.layout.JsonLayout;
import org.apache.logging.log4j.core.util.KeyValuePair;

public class Try {
    Logger logger;
    Try(){
        KeyValuePair[] kvs = {new KeyValuePair("hip", "hi")};
        System.out.println(kvs[0].toString());
        logger = (Logger) LogManager.getLogger("com.try1");
        logger.setLevel(Level.DEBUG);

        logger.addAppender(ConsoleAppender.newBuilder().setName("console.builder1")
                .setLayout(JsonLayout.newBuilder().setProperties(true)
                        .setAdditionalFields(kvs)
                        .setComplete(true)
                        .build())
                .build());
    }
    public void debug(String message){
        System.out.println(logger.isEnabled(Level.DEBUG));
        logger.debug(message);
    }
}

如果我删除.setAdditionalFields(kvs)行,一切都会神奇地工作。但是使用这个log4j什么也不打印。

g9icjywg

g9icjywg1#

由于某些原因,如果您要添加其他字段,则还需要设置默认配置:

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.apache.logging.log4j.core.layout.JsonLayout;
import org.apache.logging.log4j.core.util.KeyValuePair;

public class Try {
    Logger logger;
    Try(){
        KeyValuePair[] kvs = {new KeyValuePair("hip", "hi")};
        System.out.println(kvs[0].toString());
        logger = (Logger) LogManager.getLogger("com.try1");
        logger.setLevel(Level.DEBUG);

        logger.addAppender(ConsoleAppender.newBuilder().setName("console.builder1")
                .setLayout(JsonLayout.newBuilder()
                        .setProperties(true)
                        .setConfiguration(new DefaultConfiguration()) // magic happens here...
                        .setAdditionalFields(kvs)
                        .setComplete(true)
                        .build())
                .build());
    }
    public void debug(String message){
        System.out.println(logger.isEnabled(Level.DEBUG));
        logger.debug(message);
    }
}

相关问题