编写插件(解析%TracceId占位符)
package cn.java.log4j2.demo.plugin.fooone;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
/**
* org.apache.logging.log4j.core.pattern.MethodLocationPatternConverter
*/
@Plugin(name = "FooOnePatternLayoutPlugin", category = PatternLayout.KEY, printObject = true)
@ConverterKeys({"TraceId", "Tid"}) // 用于替换模板中的 %TraceId
public class FooOnePatternLayoutPlugin extends LogEventPatternConverter {
private static final FooOnePatternLayoutPlugin INSTANCE =
new FooOnePatternLayoutPlugin();
private FooOnePatternLayoutPlugin() {
super("TraceId", "traceId");
}
@Override
public void format(LogEvent event, StringBuilder toAppendTo) {
final StackTraceElement element = event.getSource();
if (element != null) {
toAppendTo.append(getClass().getSimpleName() + "_do_append_" + element.getMethodName());
}
}
public static FooOnePatternLayoutPlugin newInstance(final String[] options) {
return INSTANCE;
}
}
使用
<PatternLayout pattern="[%d{HH:mm:ss.SSS}] %-5level %class{36} %L %M %TraceId - %msg%xEx%n"/>