How to Mask Sensitive Data (Card Numbers) in Logs with Log4j2

adminUpdated 6 min read
In this tutorial
  1. How it works
  2. Dependencies
  3. Sample classes
  4. log4j2.xml
  5. The masking converter
  6. Testing it
  7. Improving the masking
  8. Defence in depth
  9. Summary

Say you have a class that holds payment information. You need to log this data for debugging and auditing, but you must be careful not to expose the sensitive parts. Card numbers in log files are a serious security risk. Logs are copied to monitoring tools, shared in support tickets and kept for months, and payment card industry rules (PCI DSS) forbid storing full card numbers in plain text.

Log4j2 can handle the masking for you, so a card number is hidden even if a developer accidentally logs the whole object. Here is the process.

How it works

Log4j2 formats each log line using a pattern layout, such as %d [%t] %-5level %logger - %msg%n. Each %something is handled by a pattern converter. We will write our own converter, registered under the key koore, that takes the log message, replaces anything that looks like a 16-digit card number with Xs, and writes the result. Then we use %koore instead of %msg in the pattern.

Dependencies

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.19.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.19.0</version>
</dependency>

Use the latest 2.x version available when you set up your project. Never use versions older than 2.17.1, which are affected by the Log4Shell vulnerabilities.

Sample classes

Both classes also need getters, setters and a toString() method (or Lombok’s @Data) so the card details appear in the log message.

public class Person {
    private String name;
    private String gender;
    private CardDetails cardDetails;
}

public class CardDetails {
    private String cardNumber;
    private String cvv;
    private String pin;
}

log4j2.xml

Add this file to your resources folder. The packages attribute tells Log4j2 where to find the custom converter, and %koore in the pattern calls it.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="OFF" packages="com.kooredev.blog">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %koore%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="all">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

The masking converter

package com.kooredev.blog;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Plugin(name = "LogMaskingConverter", category = "Converter")
@ConverterKeys({"koore"})
public class LogMaskingConverter extends LogEventPatternConverter {

    private static final Pattern CARD_NUMBER_PATTERN = Pattern.compile("([0-9]{16})");
    private static final String CARD_NUMBER_MASK = "XXXXXXXXXXXXXXXX";

    protected LogMaskingConverter(String name, String style) {
        super(name, style);
    }

    public static LogMaskingConverter newInstance(String[] options) {
        return new LogMaskingConverter("koore", Thread.currentThread().getName());
    }

    @Override
    public void format(LogEvent event, StringBuilder outputMessage) {
        String message = event.getMessage().getFormattedMessage();
        String maskedMessage;
        try {
            maskedMessage = mask(message);
        } catch (Exception e) {
            System.out.println("Failed while masking");
            maskedMessage = message;
        }
        outputMessage.append(maskedMessage);
    }

    private String mask(String message) {
        Matcher matcher = CARD_NUMBER_PATTERN.matcher(message);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(buffer, CARD_NUMBER_MASK);
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }
}

What each part does:

  • @Plugin(category = "Converter") registers the class with Log4j2’s plugin system.
  • @ConverterKeys({"koore"}) is the name you use in the pattern: %koore.
  • newInstance is the factory method Log4j2 calls to create the converter.
  • format receives every log event, masks the formatted message and appends the result to the output.
  • mask uses a regular expression to find every run of 16 digits and replace it.

Testing it

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Test {

    private static final Logger logger = LogManager.getLogger(Test.class);

    public static void main(String[] args) {
        CardDetails cardDetails = new CardDetails();
        cardDetails.setCardNumber("5355986478234562");
        cardDetails.setCvv("453");
        cardDetails.setPin("1234");

        Person person = new Person();
        person.setName("Dupe Adio");
        person.setGender("Female");
        person.setCardDetails(cardDetails);

        // The card number is masked in the output, so a third party cannot read it.
        logger.info("Personal data {}", person);
    }
}

The log line shows cardNumber=XXXXXXXXXXXXXXXX instead of the real number.

Improving the masking

The simple version above is a good start. For production, consider these improvements:

Keep the last four digits

Support teams often need the last four digits to identify a card. Use a capture group:

private static final Pattern CARD = Pattern.compile("\\b(\\d{12})(\\d{4})\\b");

private String mask(String message) {
    return CARD.matcher(message).replaceAll("************$2");
}

5355986478234562 becomes ************4562.

Handle other card lengths and formats

Card numbers range from 13 to 19 digits and are often written with spaces or dashes (5355 9864 7823 4562). A broader pattern such as \b(?:\d[ -]?){12,18}\d\b catches more formats. Test it carefully, though: you do not want to mask order IDs or phone numbers by mistake.

Mask other sensitive fields

CVVs and PINs should never be logged, not even masked. Under PCI DSS, the CVV must not be stored after authorisation at all. Exclude them from toString() entirely:

@Override
public String toString() {
    return "CardDetails[cardNumber=" + maskCard(cardNumber) + "]";   // no cvv, no pin
}

The same applies to passwords, BVNs and NINs, OTPs, access tokens and API keys.

Defence in depth

Log masking is a safety net, not the main protection. Combine it with:

  1. Don’t log sensitive objects in the first place. Log IDs and references (orderId, transactionRef) rather than whole objects.
  2. Safe toString() methods on any class that holds sensitive data. If you use Lombok, add @ToString.Exclude to sensitive fields.
  3. Tokenisation: let your payment provider (Paystack, Flutterwave, Stripe and so on) store card details and give you a token. Then your system never sees full card numbers at all.
  4. Restrict access to logs, and set sensible retention periods.

Summary

  • A custom Log4j2 LogEventPatternConverter can mask card numbers in every log line automatically.
  • Register it with @Plugin and @ConverterKeys, and use the key (%koore) in your pattern instead of %msg.
  • Keep the last four digits if support needs them, and handle spaces and other card lengths.
  • Never log CVVs, PINs or passwords, even masked.
  • The best protection is not logging sensitive data at all. Masking is the safety net.

New to exceptions and logging? Read checked vs unchecked exceptions next.

Ask a question or leave a comment

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