我正在尝试在 Log4j2 中编写我自己的 RewritePolicy。 documentation 指出:
这是我的 Java 类 :
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.getContextMap().put("_marker", marker.getName());
return event;
}
}
这是我的 yaml 配置 文件:
Rewrite:
name: REWRITE_APPENDER
AppenderRef:
ref: ROUTING_APPENDER
PropertiesRewritePolicy:
Property:
- name: foo
value: bar
但是我不知道如何将它注入(inject)到我的配置文件中。我怎样才能让它在运行时工作?
最佳答案
您的自定义重写策略应编码为 log4j2 插件。这使您可以在 RewriteAppender 中配置自定义 RewritePolicy。
@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;
}
}
示例配置(TODO:为包属性设置正确的值):
<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>
关于java - 如何在 log4j2 中创建自定义 RewritePolicy?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30247323/