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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Building an AI/ML Data Lake With Apache Iceberg
  • Beyond Simple Responses: Building Truly Conversational LLM Chatbots

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Non-Project Backlog Management for Software Engineering Teams
  • Role of Cloud Architecture in Conversational AI
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  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 user avatar
Julie Russell
·
Oct. 21, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
23.3K Views

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.

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

  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Building an AI/ML Data Lake With Apache Iceberg
  • Beyond Simple Responses: Building Truly Conversational LLM Chatbots

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!