本文介绍了有没有办法在Log4j2中使用RoutingAppender基于Marker路由日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用标记消息,例如:

It is possible to filter messages using markers, such as :

      <MarkerFilter marker="FLOW" onMatch="ACCEPT" onMismatch="DENY"/>

但是我正在尝试使用。我不想在多个Appender中多次过滤相同的参数。这是我的配置示例(yaml):

However I'm trying to route a message based on the marker using the RoutingAppender. I don't want to filter the same arguments multiple times in multiple Appenders. Here's my configuration sample (yaml):

Routing:
  name: ROUTING_APPENDER
  Routes:
    pattern: "$${ctx:marker}" #<-- How to use Marker here?
    Route:
      - key: MyRoutingKey
        ref: MyCustomAppender

文档规定:

但似乎没有,对于LogLevel也是如此。可以在但是我发现解决方案没有真正有效,它复制了已知信息。

However there seems to be no Lookup for Markers, same for LogLevel. It would be possible to add a custom MarkerValue or LogLevelValue in the ThreadContextMap but I don't find the solution really efficient, it duplicates known information.

是否没有记录还是不可能?是否有内置的方法可以在Lookup中访问这些值?

Is it not documented or just impossible? Should there be a built-in way to have access to those values in Lookup?

推荐答案

RoutingAppender的文档显示了ThreadContext查找,但路由也可以与其他查找一起使用。一个想法是创建自定义查找。

The documentation for RoutingAppender shows the ThreadContext lookup, but routing can also work with other lookups. One idea is to create a custom lookup.

自定义查找是作为log4j2插件实现的。要帮助log4j2找到您的插件,您可以在配置文件中启用 packages =yourCustomPackage。你的插件类需要在类路径上,所以log4j可以找到它。以下是自定义查找的插件代码:

A custom lookup is implemented as a log4j2 plugin. To help log4j2 find your plugin you can enable packages="yourCustomPackage" in your configuration file. Your plugin class needs to be on the classpath so log4j can find it. Here's the plugin code for the custom lookup:

import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;

@Plugin(name = "marker", category = "Lookup")
public class MarkerLookup implements StrLookup {

    public String lookup(String key) {
        return null
    }

    public String lookup(LogEvent event, String key) {
        final Marker marker = event.getMarker();
        return marker == null ? null : marker.getName();
    }
}

在配置文件中:

Routing:
  name: ROUTING_APPENDER
  Routes:
    pattern: "$${marker:}"
    Route:
    - key: PERFORMANCE
      ref: PERFORMANCE_APPENDER
    - key: PAYLOAD
      ref: PAYLOAD_APPENDER
    - key: FATAL
      ref: FATAL_APPENDER
    - ref: APPLICATION_APPENDER #Default route

Log4j2开发者的积分(。

Credits to the Log4j2 developers (https://issues.apache.org/jira/browse/LOG4J2-1015).

UPDATE :根据他们的说法,它应该在下一个版本(2.4)中内置。因此,之后不需要编写自定义插件。

UPDATE : According to them, it should be built-in in the next version (2.4). So no needs to write custom plugin after that.

这篇关于有没有办法在Log4j2中使用RoutingAppender基于Marker路由日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:28