Configure Log4j2 Converter Plugin -Java (Filter log messages)

Apache Log4j2 is used for printing info, error, debug, trace logging statements in enterprise applications.

Inorder to format all the log messages externally before printing in logs, we need to create Filters in Log4j 1.x versions.

In Log4j2 , we can use LogEventPatternConverter to filter/convert/format log messages before printing in the log files in server.

e.g., we can filter out any PII data format such as card numbers, dates, any particular string format before printed in the logs., so that the PII data can be effectively maintained.,(not disclosed)

Lets see how we can configure the filters/converters in Log4j2

The following versions are being used for below example to configure Log4j2.

  • Java 1.5+
  • Maven
  • Log4j Version 2.17

Create a simple Maven project with Log4j2 like in previous tutorial

Once the SetUp is done,

Please include the following the Plugin Java File to implement our filter/converter changes.

In the above Java class., we are replacing all log messages containing 6 digit numbers with empty string.

Hence all 6 digits numbers will not be printed in log message. e.g., to avoid printing any cards, serials etc.,

  • @Plugin – Annotation of Log4j2 to identify this class as a Plugin
  • @ConverterKeys – Annotation to define the key which can be used in the / xml file to print the filtered message. will be like below.

In the above log4j2 properties, we can see instead of just printing the log message %m we are printing %filteredlogmessage, which will print the log messages excluding the 6 digit numbers

[DataPatternConverter.format() method will be called for each log message before beign printed]

Also note the package name of plugin is included in log4j properties
packages = com.tutorialflow.example.config

Finally in the application, in the below code we are printing 6 digits numbers along with the log messages, however it will be removed before printing in the logs., as explained above.

The resulting logs will be printed like below.

The complete Log4j2 Converter Project is available in the following GitHub Location.,

Leave a Reply

Your email address will not be published. Required fields are marked *