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.
To disable scrubbing entirely, set scrubbing to False:
import logfire
logfire.configure(scrubbing=False)
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|_)',
]
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.
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.
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.
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_attributesisTrue, or it is unset andverboseisTrue. - A span processor is included in
additional_span_processorsthat implements anon_endhook and isn’t aBatchSpanProcessor.
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.
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.
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.
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.
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.