Is there a way to token-based logging using RoutingAppender in Log4j2

filter you can use markers, for example:

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

However, I am trying to direct a marker based message using RoutingAppender . I do not want to filter the same arguments multiple times in multiple Appenders. Here is my sample configuration (yaml):

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

The documentation provides for:

The template is evaluated for all registered Lookups and the result is used to select a route.

However, for tokens there is no Lookup , the same for LogLevel. You can add a custom MarkerValue or LogLevelValue to ThreadContextMap, but I did not find the solution really effective, it duplicates the known information.

Not documented or simply impossible? Should there be a built-in way to access these values ​​in Lookup?

+1
java logging log4j2
source share
1 answer

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

Custom search is implemented as a log4j2 plugin. To help log4j2 find your plugin, you can include packages = "yourCustomPackage" in your configuration file. Your plugin class should be in the classpath, so log4j can find it. Here is the plugin code for custom search:

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

And in the configuration file:

 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 

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

UPDATE According to them, it should be built into the next version (2.4). Therefore, after this you do not need to write a custom plugin.

+2
source share

All Articles