我尝试了Extending Log4j2和Create Custom Pattern using log4j2 in java中的示例,现在我想在日志中添加两个字段。为了得到这个,我需要做些什么改变?
答案 0 :(得分:1)
请参阅本手册https://logging.apache.org/log4j/log4j-2.2/manual/plugins.html#Converters
如果您想要多个字段,例如时间和名称,您可以创建两个单独的转换器,将这些数据提供给日志。
例如,您有 MyNamePatternConverter ,在这里我们可以提供别名 whatIsMyName 和 myName 。在日志模式中,我们可以使用其中任何一种。
@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()));
}
}
我们将把它们放在名为 converter 的单独包中。
<?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。
创建一个示例Main类来测试它。
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