Skip to content

Log Masking

A credential in a function's input or in the configuration is not the problem; a credential in the application log is. The pack masks what its own lines write (what the log holds). What the lines of your functions hold is yours to know, and this extension is the tool for it: it applies the rules of a log-masking.yaml file to a line before the pack's handler writes it.

It is elective: nothing is filtered until an application adopts it, and it costs time on every line. It is a best effort: it masks what its rules match and nothing else. The shipped rule file is a sample to start from, and not a list of what is personal data.

The extension is the Python twin of the Java engine's extensions/log-masking and of the Rust engine's mercury-log-masking crate (Log Masking in the engines' guides), and the Node.js pack carries the same. The four read the same rule file, and a vector file that the four repositories share, log-masking-vectors.json, holds the sample rules to the same result in each.

Adopt it

  1. Copy extensions/log-masking/log_masking.py next to your application file.
  2. Copy extensions/log-masking/sample/log-masking.yaml into the resources folder next to your application file, and make the rules yours.
  3. Call install() in the application file, before the functions it registers:
import log_masking

log_masking.install()

from mercury_composable import preload

The module next to the application file is found under python app.py and under mercury-serve app.py. When the rules are in force the log says so:

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

install() reads classpath:/log-masking.yaml, the file in the resources folder. install("file:/etc/my-app/log-masking.yaml") reads a file elsewhere. A line that is written before the call is not filtered, so call it first.

The pack's hook. The extension is one user of a call of the pack:

from mercury_composable import add_log_filter

add_log_filter(my_filter)   # a logging.Filter, or a callable that takes the record

add_log_filter() adds a filter to the handler that the pack installs on the root logger. Every line of the application passes through that handler, the trace records included. An installation that replaces this extension writes a filter of its own and adds it the same way. A handler that the application adds to a logger by itself is not the pack's, and the filter is not on it.

A filter changes the record it is given and answers true, as this extension's does. A record that a filter returns in its place is written from Python 3.12 on; Python 3.11 reads such an answer as true and writes the record it had, unchanged.

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 Python's regular expressions backtrack, and the time of some patterns grows with the square of the text or faster.

Writing a pattern

The same rule file is read in the four runtimes, so keep a pattern to what their regular-expression engines 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. Python accepts more than the subset, and a rule that uses it is a rule for this runtime only.

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

  • Outside ASCII. \d, \w, \s and \b are Unicode here and in the Rust engine, and ASCII in the Java 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. $ also matches before a line feed at the end of the text here and 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. The interpreter cannot be stopped inside a match, so such a rule holds the application for that time.

What it reads, and what it does not reach

It reads:

  • A line's message as a text, after its arguments are formatted. log.info("customer %s granted with premium class", customer_email) 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(key_values), which the JSON formats write as an object, and the trace record is one. With {"customer": customer_email, "class": "premium"} every format writes {"customer": "<e-mail>", "class": "premium"}. The message keeps its shape and its keys.
  • The text of an attached exception, of its cause, of the exception that was being handled when it was raised, of its notes and of the members of an exception group. The exception is written under its own class name, with the masked text and its own frames; a group is written as the built-in group class.

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 formatter adds after the filter: the correlation id, the trace ids, the trace path and the keys of update_context(). 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 Python traceback prints the source line of each frame, so a literal on a raise line is written as the file holds it.
  • A line that does not pass through the pack's handler: what a library prints to the console, and a handler that the application added itself.
  • What leaves the application by another way: the spans that the OpenTelemetry forwarder exports, the transcript audit store, an error response.

The application's own objects are never changed: the map that it logged and the exception that it raised are the ones they were. The filter puts a copy on the record where a rule changed something, and a record that no rule changes is left as it was.

The trace record passes through the filter. distributed.tracing writes its record through the logger, whatever the log level says, so your rules read the record's values, the annotations among them, and the record keeps its shape.

A rule that fails while it reads a line does not fail the code that logged the line: the line is written as [log-masking: this line could not be read].

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 extension cannot use stops the start of the application: install() logs the reason and ends the process with exit code 1. A filter that quietly filters nothing is worse than none. The reason names the file, the key at fault and the rule:

Log masking cannot start - log-masking: classpath:/log-masking.yaml: 'masking.rules[1]' (card number) has a pattern that does not compile - missing ), unterminated subpattern near index 3

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 - yes is a text in YAML 1.2.2.

MaskingRules.load() raises MaskingError with the same reason, for a program that reads a rule file without install().

What it costs

The filter runs on every line that the pack's handler writes. Measured on a developer's laptop with Python 3.14, through a handler that formats each line in the compact format 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 filter about 155,000
With the four sample rules about 85,000

That is about 5 microseconds for a line. The figures depend on your rules and on your lines: extensions/log-masking/dev/cost.py is the measurement, to run against the rules of your own.