Skip to content

Logfire: Guide for Scrubbing Sensitive Data from Logs

The Logfire SDK scans for and redacts potentially sensitive data from logs and spans before exporting them.

Scrubbing applies only to data that the SDK has not sent yet. If sensitive data already reached Logfire, delete it with a deletion job.

Disabling scrubbing

To disable scrubbing entirely, set scrubbing to False:

import logfire

logfire.configure(scrubbing=False)

Scrubbing more with custom patterns

By default, the SDK looks for some sensitive regular expressions. To add your own patterns, set extra_patterns to a list of regex strings:

import logfire

logfire.configure(scrubbing=logfire.ScrubbingOptions(extra_patterns=['my_pattern']))

logfire.info(
    'Hello',
    data={
        'key_matching_my_pattern': 'This string will be redacted because its key matches',
        'other_key': 'This string will also be redacted because it matches MY_PATTERN case-insensitively',
        'password': 'This will be redacted because custom patterns are combined with the default patterns',
    },
)

Here are the default scrubbing patterns:

[
    'password',
    'passwd',
    'mysql_pwd',
    'secret',
    'auth(?!ors?\\b)',
    'credential',
    'private[._ -]?key',
    'passphrase',
    '(?:signing|hmac)[._ -]?key',
    'api[._ -]?key',
    'session',
    'cookie',
    'social[._ -]?security',
    'credit[._ -]?card',
    'logfire[._ -]?token',
    '(?:access|refresh|bearer|(?:\\b|_)id)[._ -]?token',
    'security[._ -]?token',
    'pylf_v\\d+_',
    '(?:\\b|_)csrf(?:\\b|_)',
    '(?:\\b|_)xsrf(?:\\b|_)',
    '(?:\\b|_)jwt(?:\\b|_)',
    '(?:\\b|_)ssn(?:\\b|_)',
]

Scrubbing less with a callback

On the other hand, if the scrubbing is too aggressive, you can pass a function to callback to prevent certain data from being redacted.

The function will be called for each potential match found by the scrubber. If it returns None, the value is redacted. Otherwise, the returned value replaces the matched value. The function accepts a single argument of type logfire.ScrubMatch.

Here’s an example:

import logfire


def scrubbing_callback(match: logfire.ScrubMatch):
    # `my_safe_value` often contains the string 'password' but it's not actually sensitive.
    if match.path == ('attributes', 'my_safe_value') and match.pattern_match.group(0) == 'password':
        # Return the original value to prevent redaction.
        return match.value


logfire.configure(scrubbing=logfire.ScrubbingOptions(callback=scrubbing_callback))

Logfire scrubs a value before checking whether its key matches a pattern. This includes strings and values inside dictionaries, lists, and JSON-encoded containers. Your callback for a matching key receives the scrubbed value, so it can return that value unchanged or return a subset of a container. If it returns a different value, Logfire uses that replacement without scrubbing it again. For most safe keys, Logfire skips pattern matching inside their values; structured message attributes are treated differently, as described below.

For a Pydantic validation error, Logfire checks field names in loc (the path to the field that failed) like keys for input (the rejected value). It checks the innermost field first. Your callback receives the full loc path for each matching name. For a missing-field error, input is the container missing that field, so Logfire skips the absent field name and checks the parent names and keys inside the container.

Logfire also checks JSON-encoded arrays and objects nested inside strings. If scrubbing changes a value inside more than four such strings, Logfire replaces the nested string with [Scrubbed due to deeply nested JSON]. The marker also replaces any callback replacement inside that string, along with other data there. JSON with no scrubbing changes stays unchanged.

If the callback returns a value unchanged (or returns an equal copy of the same type), Logfire checks other patterns that match at the same position, then later positions in the same key or string value. The callback may run more than once for one key or value. A different returned value is used as the final value. After 100 allowed matches in one string, Logfire redacts the value to limit the search cost.

Masking part of a string

Use transform_string to replace sensitive text while keeping the rest of a value. The callback receives the string and its path:

import re

import logfire
from logfire.types import StringValue


def mask_email(item: StringValue) -> str:
    if '@' not in item.value:
        return item.value
    return re.sub(r'\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b', '[email]', item.value)


logfire.configure(scrubbing=logfire.ScrubbingOptions(transform_string=mask_email))
logfire.info('Contact {email}', email='alice@example.com')

The exported email attribute and formatted message contain [email]. The callback runs on string values inside JSON and under keys that are exempt from pattern matching. Pattern matching runs on the returned string where permitted.

The callback runs for every string the scrubber reaches, including large values. Logfire excludes control and source metadata such as logfire.span_type and code.filepath. The email regex above is illustrative and can take quadratic time on long strings containing @; the initial @ check does not prevent that. Check the performance of your matcher on the longest values you expect to log.

Logfire transforms logfire.msg when it is a string. If this attribute contains a nonempty, non-string value, Logfire leaves the value and any strings inside it unchanged.

When Logfire scrubs spans

Scrubbing span attributes is slow, so it happens in a background thread when possible. It will instead happen on the calling thread if any of the following are true:

  • Console logging is enabled and prints attributes, i.e. include_attributes is True, or it is unset and verbose is True.
  • A span processor is included in additional_span_processors that implements an on_end hook and isn’t a BatchSpanProcessor.

Message template fields are scrubbed on the calling thread. If transform_string is configured, Logfire also transforms the assembled message, tags, and displayed exception details on that thread. Keep objects with large string representations out of messages. If neither condition above applies, log large objects as span attributes so they can be scrubbed in the background.

Security tips

Use message templates

Pattern matching checks message fields rather than the assembled message. For example, this:

logfire.info('User details: {user}', user=User(id=123, password='secret'))

…may log something like:

User details: [Scrubbed due to 'password']

…but this:

user = User(id=123, password='secret')
logfire.info('User details: ' + str(user))

will log:

User details: User(id=123, password='secret')

This is necessary so that safe messages such as ‘Password is correct’ are not redacted completely.

Using f-strings (e.g. logfire.info(f'User details: {user}')) is safe if inspect_arguments is enabled (the default in Python 3.11+) and working correctly. See here for more information.

In short, don’t format the message yourself. This is also a good practice in general for other reasons.

The transform_string callback will run on the assembled message.

Logging libraries format their own messages, so the same applies to them: pattern matching checks the arguments Logfire records as attributes, but not the formatted message. The transform_string callback still runs on that message. See standard library logging, Loguru, and structlog positional arguments.

Keep sensitive data out of URLs

The attribute "http.url" which is recorded by OpenTelemetry instrumentation libraries is considered safe so that URLs like "http://example.com/users/123/authenticate" are not redacted.

As a general rule, not just for Logfire, assume that URLs (including query parameters) will be logged, so sensitive data should be put in the request body or headers instead.

Use parameterized database queries

The "db.statement" attribute which is recorded by OpenTelemetry database instrumentation libraries is considered safe so that SQL queries like "SELECT secret_value FROM table WHERE ..." are not redacted.

Use parameterized queries (e.g. prepared statements) so that sensitive data is not interpolated directly into the query string, even if you use an interpolation method that’s safe from SQL injection.

Scrub rejected values in validation errors

Pydantic validation errors store the rejected value under input and the field’s path under loc. Logfire checks each field name in loc against your scrubbing patterns and redacts a matching field’s input. This applies to recorded validation exceptions, FastAPI and Pydantic integration errors, and error data you log yourself. Pattern scrubbing leaves field names in loc visible so you can identify which field failed; a configured transform_string callback can still change them. A scrubbing callback receives the field path when it decides whether to redact the value.

When Logfire records a Pydantic ValidationError, it also uses the redacted value in the exception message, stack trace, and span status. For example, a rejected password appears as input_value="[Scrubbed due to 'password']" instead of the original value. The exception in your application is unchanged.

Custom validation messages can contain the rejected value in other text. If a validator writes the value into its error message or derives text from it, that text may still reveal it. Avoid including sensitive values in custom error messages. You can also use Pydantic’s hide_input_in_errors=True model setting to omit rejected values from its rendered validation errors entirely.

LLM and AI messages

For gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions, and pydantic_ai.all_messages, Logfire checks nested field names for sensitive patterns. For example, it redacts the value of a password field inside a tool call. It does not check the message’s string values for patterns, so ordinary text containing words such as “password” or “secret” remains visible. A configured transform_string callback still runs on those strings.

This avoids false positives in ordinary conversation while catching some structured tool arguments and responses. It does not detect sensitive content in prose or under an innocuous field name.

If your LLM interactions might contain sensitive data, exclude message content from logging entirely rather than relying on pattern scrubbing. For example, with Pydantic AI:

import logfire

logfire.configure()
logfire.instrument_pydantic_ai(include_content=False)

This will still log spans for LLM calls and agent runs with timing and metadata, but will exclude the actual prompts, completions, and tool call arguments/responses.