gpt4 book ai didi

java - 如何在 log4j2 中创建自定义 RewritePolicy?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:43:44 26 4
gpt4 key购买 nike

我正在尝试在 Log4j2 中编写我自己的 RewritePolicy。 documentation指出:

RewritePolicy is an interface that allows implementations to inspect and possibly modify LogEvents before they are passed to Appender. RewritePolicy declares a single method named rewrite that must be implemented. The method is passed the LogEvent and can return the same event or create a new one.

这是我的 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:为 packages 属性设置正确的值):

<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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com