Skip to content

Log Masking

Guide: an elective filter for the application log, with its rules in a configuration file.

At a glance

  • What - the extension extensions/log-masking: a rewrite step for the log4j2 configuration that applies the rules of your log-masking.yaml to a line before an appender writes it.
  • How - add the dependency, put a log-masking.yaml into your resources, and name the step in your copy of the log4j2 file. A rule is a name, a regular expression and a replacement.
  • Elective - nothing is masked until you adopt it, and it costs time on every line.
  • A best effort - it masks what your rules match, in what it reads, and nothing else. It is not a detector of credentials or of personal data, and no rule set is complete.
  • For an installation whose log must not hold certain values that its own lines, or its users' data, may carry.

The engine masks what it writes itself where it can tell that a value is a credential: the user id and password of a URL, four credential headers of the API fetcher, the value of a refused setting. It does not know what your own lines hold. A line such as log.info("customer {} granted with premium class", customerEmail) is yours, and so is the decision whether an e-mail address may be in the log. This extension is the place for that decision: a small filter that you adopt as it is, extend with rules of your own, or replace with a step of your own.

It is a best effort. A rule masks the text that its pattern matches. A value that no rule matches is written as it is, and so is everything that the filter does not read (below). Treat it as one layer: the first is not to log a secret at all.

Adopt it

Three steps. The module's jar carries a sample of each file in its folder log-masking/, and the same files are in the repository under extensions/log-masking/src/main/resources/log-masking/.

1. The dependency.

<dependency>
    <groupId>org.platformlambda</groupId>
    <artifactId>log-masking</artifactId>
    <version>x.y.z</version>
</dependency>

Use the version of your platform-core.

2. The rule file. Copy the sample log-masking.yaml into the resources folder of your application and make it yours. The sample is a few labelled rules to start from. It is not a list of what is personal data: what the lines of your installation hold is for you to know.

3. The step in the log4j2 file. Copy log4j2.xml, log4j2-json.xml and log4j2-compact.xml from the same folder into the resources folder of your application; the engine picks one of the three by log.format, as Customize log4j configuration describes. Each file is the engine's own with one step added: the appender is wrapped in log4j2's Rewrite appender, and the rewrite policy is this module's LogMasking.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <JsonLogger name="JsonLogger"/>
        <!-- a line passes through the rules of log-masking.yaml before the appender writes it -->
        <Rewrite name="Masked">
            <AppenderRef ref="JsonLogger" />
            <LogMasking rules="classpath:/log-masking.yaml" />
        </Rewrite>
    </Appenders>
    <Loggers>
        <Root level="${env:LOG_LEVEL:-INFO}" additivity="false">
            <AppenderRef ref="Masked" />
        </Root>
    </Loggers>
</Configuration>

If you already have a log4j2 file of your own, add the Rewrite element to it and point your loggers at it. The rules attribute takes a classpath: or a file: location and may be left out, in which case the file is classpath:/log-masking.yaml.

When the application starts, one line says what is in force:

Log masking is in force: 4 rule(s) of classpath:/log-masking.yaml, max.length 8192

If the module is on the class path and the log4j2 file names no LogMasking step, a warning says so, and nothing is masked.

The rule file

log-masking.yaml is written in YAML 1.2.2.

masking:
  max.length: 8192
  rules:
    - name: 'bearer token'
      pattern: 'Bearer\s+([A-Za-z0-9._~+/=-]+)'
    - name: 'secret in name=value text'
      pattern: '(?:password|passwd|secret|token|api[_-]?key)["'']?\s*[=:]\s*["'']?([^\s"'',;&]+)'
      ignore.case: true
    - name: 'e-mail address'
      pattern: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}'
      replacement: '<e-mail>'
    - name: 'card number in groups of four digits'
      pattern: '\b\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{4}\b'
      replacement: '<card number>'
Key Meaning Default
masking.max.length The longest text, in characters, that a pattern runs against 8192
masking.rules[] The rules, applied in the file's order, each to the result of the one before at least one
name What the rule is for; an error text names the rule by it required
pattern A regular expression required
replacement The text written in place of what the rule replaces; a literal text, not a template ***
ignore.case true to match letters in either case false

What a rule replaces. What its pattern matches or, when the pattern has a capture group, its first group only. So a rule can keep a name and mask its value: with the second rule above, password=sample-word is written password=***. A match in which the first group took no part is left as it is, and so is a span of no characters.

The order matters. Each rule reads what the rules before it wrote. In the sample the rule for a named secret comes before the rule for an e-mail address, so token=someone@example.com is written token=***.

max.length. A text of more than max.length characters is cut at that length before the rules read it, and a mark follows what is written:

... the first 8192 characters, as the rules leave them ... [log-masking: cut at 8192 characters]

What the rules did not read is not written as if they had. The bound is there because a regular expression of the Java engine backtracks, and the time of some patterns grows with the square of the text or faster.

Writing a pattern

The same rule file is read by the Rust engine's crate mercury-log-masking, so keep a pattern to what the regular-expression engines of the runtimes share:

  • In: literals, character classes, \d, \w, \s, \b, ., quantifiers (greedy and lazy), alternation, groups - capturing and (?:...) - and the anchors ^ and $.
  • Not in: look-ahead and look-behind, back-references, possessive quantifiers and atomic groups, named groups, inline flags such as (?i), Unicode property classes such as \p{L}, and set operations inside a class (&&, --, ~~). Write a literal {, }, [ or ] with a backslash.

The subset is declared here and not enforced by a check. The Java engine accepts more than the subset, and a rule that uses it is a rule for this runtime only.

Where the engines differ, write the rule so that it does not depend on it:

  • Outside ASCII. \d, \w, \s and \b are ASCII in the Java engine and Unicode in the Rust engine. A rule that must match a letter or a digit outside ASCII names its characters in a class of its own.
  • A line break. A pattern is written for a text on one line. . matches any character but a line feed, in both engines. $ also matches before a line feed at the end of the text in the Java engine, and only at the end in the Rust engine.

For speed:

  • A pattern that begins with a repetition, such as the sample's rule for an e-mail address, is tried from every position of the text. Begin a pattern with a literal where the value has one.
  • Avoid a repetition inside a repetition, such as (\w+\s*)+: on a text that almost matches, its time grows very fast, on a short text too.
  • Prefer a class to alternatives inside a repetition: [a-z-]+ and not (?:[a-z]|-)+. The Java engine takes a stack frame for each repeat of such a group and can run out of stack on a long text. The module catches that: the line is written with [log-masking: the rule '...' could not read this text] in place of the text, and the thread that logged it goes on.

What it reads, and what it does not reach

It reads:

  • A line's message as a text. log.info("customer {} granted with premium class", customerEmail) is written customer <e-mail> granted with premium class with the sample rules.
  • Each text value of a structured message, at any depth. A structured message is a map logged as log.info("{}", keyValues), which the JSON formats write as an object, and the trace record is one. With Map.of("customer", customerEmail, "class", "premium") the JSON formats write {"customer": "<e-mail>", "class": "premium"} and the text format writes {customer=<e-mail>, class=premium}. The message keeps its shape and its keys, in the order that the map gives them.
  • The text of an attached exception, and of its causes and suppressed exceptions. The exception is written under its own class name, with the masked text and its own frames.

It does not reach:

  • The key of a value in a structured message. A rule sees each text value on its own. The sample's rule for a named secret masks password=sample-word in a text and does not see a map's entry password with the value sample-word. Mask such a value by a rule for its shape, or do not log it.
  • A value in a structured message that is no text, map or list: a number, a date, an object of your own.
  • The context block of the JSON formats, which the appender adds after the step: the correlation id, the trace ids, the trace path and the keys of updateContext. A path parameter and a value that the application puts into the context are written there as they are.
  • The frames of a stack trace.
  • A line that does not pass through the logger: what a library prints to the console, and log4j2's own status lines.
  • What leaves the application by another way: the spans that the OpenTelemetry forwarder exports, the transcript audit store, a journaled route's recorder, an error response.

The application's own objects are never changed: the map that it logged and the exception that it threw are the ones they were, and the step writes a copy where a rule changed something.

The trace record passes through the step. distributed.tracing writes its record through the logger, so your rules read the record's values, the annotations among them, and the record keeps its shape (see What a trace records).

When the rules cannot be used

A rule file that is not there, that is not a YAML document, or that holds a rule the module cannot use stops the start of the application. A filter that quietly filters nothing is worse than none. The line Application cannot start because the rules of the log filter cannot be used gives the reason, which names the file, the key at fault and the rule:

log-masking: classpath:/log-masking.yaml: 'masking.rules[1]' (card number) has a pattern that does not compile - Unclosed group near index 7

Refused: a file without the masking section or without a rule; a rule without a name or a pattern; a pattern that does not compile; a key that is not one of the file's, such as a rule option with a slip in its name; a max.length that is not a whole number of 1 or more; a replacement that is not a text; an ignore.case that is not true or false.

Until the process ends, the step withholds every line and writes the reason in its place, so that nothing is written unfiltered. The same holds where nothing stops the start, such as a program that uses the log4j2 file without the engine's start-up.

What it costs

The step runs on every line that an appender would write. Measured on a developer's laptop, through a logger whose appender formats each message and writes nowhere, with an even mix of a plain line, a line with an e-mail address and a trace record:

Lines per second
Without the module 2,000,000 to 3,000,000
With the four sample rules about 110,000

That is about 9 microseconds for a line. An appender that writes to a console spends more than that on a line of its own accord, so the share of the step is smaller there. The figures depend on your rules and on your lines: LogMaskingCostTest in the module is the measurement, to run against the rules of your own.

Design notes

  • Why elective. A detector of credentials or personal data in the engine would be a set of patterns that is never complete, it would run on every line of every installation, and it would read as a promise. What a line may hold is an installation's decision, so the rules are its file.
  • Why a rewrite policy. It is log4j2's own extension point, in front of any appender, the engine's two JSON appenders and the console among them. The engine needs no change for it.
  • Why the first group. A log is read by people who search it. password=*** says that a password was there; a line with the whole match replaced does not.
  • The same file in the Rust engine. Its crate mercury-log-masking reads the same log-masking.yaml, and a vector file that the two repositories share, log-masking-vectors.json, holds the sample rules to the same result in both.