本文介绍了如何在log4j2中创建自定义RewritePolicy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Log4j2中编写自己的RewritePolicy. 文档指出:

I'm trying to code my own RewritePolicy in Log4j2. The documentation states that :

这是我的 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

但是我不知道如何将其注入到我的配置文件中.如何使它在运行时工作?

However I have no idea how to inject it in my configuration file. How can I make it work at runtime?

推荐答案

您的自定义重写策略应编码为log4j2插件.这使您可以在RewriteAppender中配置自定义RewritePolicy.

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;
    }
}

示例配置(TODO:为包属性设置正确的值):

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>

这篇关于如何在log4j2中创建自定义RewritePolicy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 01:27