问题描述
您的自定义重写策略应编码为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>
解决方法
我正在尝试在Log4j2中编写自己的RewritePolicy。该文档指出:
RewritePolicy是一个接口,允许实现在将LogEvent传递给Appender之前检查并可能对其进行修改。RewritePolicy声明一个必须执行的名为rewrite的方法。该方法通过LogEvent传递,并且可以返回相同事件或创建一个新事件。
这是我的 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
但是我不知道如何将其注入到我的配置文件中。如何使其在运行时起作用?