I am using log4j2(version - 2.5) and I am trying write a message converter plugin which will mask some of the know patterns of the log message.
@Plugin(name = "CustomeMasking",
category = "Converter")
@ConverterKeys({"m"})
public class MyCustomFilteringLayout extends LogEventPatternConverter {
}
When I run my web application with this plugin then I see this warn message
WARN Converter key 'm' is already mapped to 'class org.apache.logging.log4j.core.pattern.MessagePatternConverter'. Sorry, Dave, I can't let you do that! Ignoring plugin [class MyCustomFilteringLayout].
After exploring log4j2 site I have found these references.
Reference
If multiple Converters specify the same ConverterKeys, then the load order above determines which one will be used. For example, to override the %date converter which is provided by the built-in DatePatternConverter class, you would need to place your plugin in a JAR file in the CLASSPATH ahead of log4j-core.jar. This is not recommended; pattern ConverterKeys collisions will cause a warning to be emitted. Try to use unique ConverterKeys for your custom pattern converters.
I need help to understand how can I write my custom converters for m/msg. Is there any better way to do it?
Additional Details: I have created shaded jar for MyCustomFilteringLayout. Reason why I am doing this way is that I want to keep masking logic separate from application.
Updated
I have created converter for my own key which looks like this,
@Plugin(name = "CustomeMasking",
category = "Converter")
@ConverterKeys({"cm"})
public class MyCustomFilteringLayout extends LogEventPatternConverter {
}
Here I can't write another converter for same ConverterKeys - cm? Now my log4j2.xml has this pattern layout,
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %cm %ex%n</Pattern>
</PatternLayout>
Your update solves the problem and answers the question how to replace the built-in message converter with a custom one. It needs a unique key.
Sounds like you want to parameterize your pattern. Many patterns take an options
parameter. You can use this to control behavior, so specifying %cm{key1} in your layout pattern will produce different results than %cm{key2}.
For an example of a converter that takes parameters, see the source code of the MdcPatternConverter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With