gpt4 book ai didi

Java Log4j2 转换器类别插件添加多个自定义字段到日志

转载 作者:行者123 更新时间:2023-12-02 13:00:16 24 4
gpt4 key购买 nike

我尝试了 Extending Log4j2 中的示例和 Create Custom Pattern using log4j2 in java现在我想向日志添加两个字段。我需要做哪些改变才能得到这个?

最佳答案

请参阅本手册 https://logging.apache.org/log4j/log4j-2.2/manual/plugins.html#Converters

如果您想要多个字段,例如时间名称,您可以创建两个单独的转换器来向日志提供该数据。

例如您有MyNamePatternConverter,这里我们可以提供别名whatIsMyNamemyName。在日志模式中,我们可以使用其中任何一个。

@Plugin(name="MyNamePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys(value = {"whatIsMyName", "myName"})
public class MyNameConverter extends LogEventPatternConverter {

protected MyNameConverter(String name, String style) {
super(name, style);
}

public static MyNameConverter newInstance(String[] options) {
return new MyNameConverter("My name Converter", "name");
}

public void format(LogEvent event, StringBuilder toAppendTo) {
toAppendTo.append("Yuriy");
}
}

TimePatternConverter

@Plugin(name = "TimePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys(value = {"timeIsNow", "timeNow", "now"})
public class TimeConverter extends LogEventPatternConverter {
protected TimeConverter(String name, String style) {
super(name, style);
}

public static TimeConverter newInstance(String[] options) {
return new TimeConverter("Time Converter", "now");
}

public void format(LogEvent logEvent, StringBuilder toAppendTo) {
toAppendTo.append(new SimpleDateFormat("HH:mm").format(new Date()));
}
}

我们将把它们两个放在名为转换器的单独包中。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns="http://logging.apache.org/log4j/2.0/config"
status="OFF" packages="converters">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="Time is now %timeIsNow and my name is %whatIsMyName, %m%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.apache.log4j.xml" level="all" />
<Root level="all">
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>

提供log4j2.xml。

并创建一个示例主类来测试它。

public class Main {
private static final Logger logger = LogManager.getLogger(ResolverUtil.Test.class);
public static void main(String[] args) {
logger.info("Hello log4j2");
logger.debug("This is debug message");
}
}

这将产生这样的输出:

Time is now 20:40 and my name is Yuriy, Hello log4j2
Time is now 20:40 and my name is Yuriy, This is debug message

关于Java Log4j2 转换器类别插件添加多个自定义字段到日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44326465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com