Your custom rewrite policy should be coded as a log4j2 plugin. This enables you to configure your custom RewritePolicy in a RewriteAppender.
@Plugin(name = "InjectMarkerPolicy", category = "Core",
elementType = "rewritePolicy", printObject = true)
public final class MarkerInjectorRewritePolicy implements RewritePolicy {
@Override
public LogEvent rewrite(final LogEvent event) {
final Marker marker = event.getMarker();
if (marker == null)
return event;
// If there's a Marker, add it to the ThreadContextMap
// so the RoutingAppender can properly routes log messages
// event's context map is immutable, so need to make a copy...
Map<String, String> mdc = new HashMap<>(event.getContextMap());
mdc.put("_marker", marker.getName());
LogEvent result = new Log4jLogEvent(event.getLoggerName(), event.getMarker(),
event.getLoggerFqcn(), event.getLevel(), event.getMessage(),
event.getThrown(), mdc, event.getContextStack(),
event.getThreadName(), event.getSource(), event.getTimeMillis());
return result;
}
}
Example config (TODO: set correct value for packages attribute):
<Configuration status="trace" packages="my.rewritepolicy.plugin.package">
<Appenders>
<Console name="STDOUT">
<PatternLayout pattern="[%-5level] %c{1.} %m%n"/>
</Console>
<Rewrite name="Rewrite">
<InjectMarkerPolicy />
<AppenderRef ref="STDOUT"/>
</Rewrite>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="Rewrite"/>
</Root>
</Loggers>
</Configuration>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…