How To Mask Sensitive Data
In this quick tutorial, we'll show you how to intercept data before libraries log it into a file by creating a Rewrite Policy for your sensitive data.
Join the DZone community and get the full member experience.Join For Free
You can leverage the Log4j Framework by Apache to make changes to the message logger during application execution. In the case where you are dealing with sensitive data in your application, it is difficult to mask at the code level because so many of the libraries log data that you do not have control over the message input. What Log4j offers is a way to intercept the data before it logs it to a file by creating a Rewrite Policy.
You need to create a Java class that implements the Apache RewritePolicy class. This will give you access to the log data before it is logged such as the logger name, level, message, throwable, etc... You will notice that you need to invoke the class as a factory method. In this case we are not passing any arguments so we just call the constructor and there is no logic involved. To pass arguments you need to annotate them with @PluginAttribute(“attributeName”) and then pass them to the constructor when instantiating the object.
Below in an example of how you can wire in your Rewrite Policy for Log4j.
In this example;
- The AsyncRoot references the Rewrite Appender
- The Rewrite Appender references the Rewrite Policy found in the package specified in the Configuration node
- The Rewrite Appender references the Rolling File Appender
When you run your application you will notice that the logger is intercepted after it writes to the console and before it writes to the log file. If you add a Console Appender and reference it from the Rewrite Appender the console will show log every line twice, once with the modified log line and one without. Therefore it is better to leave it as just the Rolling File Appender so that no sensitive data is persisted and the console stays legible.
Published at DZone with permission of Julie Russell. See the original article here.
Opinions expressed by DZone contributors are their own.