DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Share Delta Lake Tables Between Databricks and Snowflake
  • Why Vulnerability Management Fails Without Reliable Asset Data
  • Engineering Audit-Ready Data Pipelines for Regulatory Reporting
  • Moving 900+ GB of Prometheus Without a Cutover Weekend

Trending

  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • YAGNI in the Age of AI Coding
  • How to Migrate From LangChainGo to Genkit Go

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. How To Mask Sensitive Data

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.

By 
Julie Russell
·
Oct. 21, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
24.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

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. 

Java
 




x


 
1
package com.diamondedgeit.custom.logger;
2
 
3
import org.apache.logging.log4j.Logger;
4
import org.apache.logging.log4j.core.LogEvent;
5
import org.apache.logging.log4j.core.appender.rewrite.RewritePolicy;
6
import org.apache.logging.log4j.core.config.plugins.Plugin;
7
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
8
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
9
import org.apache.logging.log4j.message.SimpleMessage;
10
import org.apache.logging.log4j.status.StatusLogger;
11
 
12
@Plugin(name = "LogInterceptor", category = "Core", elementType = "rewritePolicy", printObject = true)
13
public class CustomLogInterceptor implements RewritePolicy {
14
    protected static final Logger logger = StatusLogger.getLogger()
15
    
16
      private CustomLogInterceptor() { }
17
              
18
      @PluginFactory
19
      public static CustomLogInterceptor createPolicy() {
20
        return new CustomLogInterceptor();
21
      }
22
              
23
      @Override
24
      public LogEvent rewrite(LogEvent event) {
25
        String message = event.getMessage().getFormattedMessage();
26
                               
27
        // write your code to manipulate your message here
28
        message = message.replaceAll("password", "*******");
29
                                                             
30
        return Log4jLogEvent.newBuilder()
31
            .setLoggerName(event.getLoggerName())
32
            .setMarker(event.getMarker())
33
            .setLoggerFqcn(event.getLoggerFqcn())
34
            .setLevel(event.getLevel())
35
            .setMessage(new SimpleMessage(message))
36
            .setThrown(event.getThrown())
37
            .setContextMap(event.getContextMap())
38
            .setContextStack(event.getContextStack())
39
            .setThreadName(event.getThreadName())
40
            .setSource(event.getSource())
41
            .setTimeMillis(event.getTimeMillis())
42
            .build();
43
      }
44
}


 

Log4j XML

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. 

XML
 
xxxxxxxxxx
1
21
 
1
<?xml version="1.0" encoding="utf-8"?>
2
<Configuration status="trace" packages="com.deic.custom.logger">
3
    <Appenders>
4
        <RollingFile name="file" fileName="${sys:logs.home}sys:file.separator}test.log"
5
            filePattern="${sys:logs.home}${sys:file.separator}test-%i.log">
6
            <PatternLayout pattern="%d [%t] %-5p %c - %m%n" ></PatternLayout>
7
            <SizeBasedTriggeringPolicy size="10 MB" ></SizeBasedTriggeringPolicy>
8
            <DefaultRolloverStrategy max="10"></DefaultRolloverStrategy>
9
        </RollingFile>
10
        <Rewrite name="rewrite">
11
            <LogInterceptor ></LogInterceptor>
12
            <AppenderRef ref="file"></AppenderRef>
13
        </Rewrite>
14
    </Appenders>
15
    <Loggers>
16
        // some loggers here
17
       <AsyncRoot level="INFO">
18
            <AppenderRef ref="rewrite" ></AppenderRef>
19
       </AsyncRoot>
20
    </Loggers>
21
</Configuration>

Data (computing)

Published at DZone with permission of Julie Russell. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Share Delta Lake Tables Between Databricks and Snowflake
  • Why Vulnerability Management Fails Without Reliable Asset Data
  • Engineering Audit-Ready Data Pipelines for Regulatory Reporting
  • Moving 900+ GB of Prometheus Without a Cutover Weekend

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook