PII in logs is one of those problems that nobody is responsible for and everybody causes. A developer adds a debug log to investigate a customer ticket. A library logs an HTTP request including the Authorization header. A failed payment generates a stack trace with the card number in the message. None of these are obviously malicious. All of them end up in centralized logging where developers, vendors, and contractors can search them.
The cost of getting this wrong is real. GDPR and CCPA carry fines. SOC 2 auditors look at logs. PCI scope expands when card numbers appear in logs. Even without regulation, a leaked log dataset is a meaningful breach.
This guide is about the controls that consistently keep PII out of observability pipelines without forbidding developers from logging anything useful.
What PII Actually Looks Like in Logs
A partial inventory of how PII commonly leaks:
- Direct logging. A developer writes
log.info("User email: " + email)for debugging and forgets to remove it. - Request / response logging. Middleware logs every request body or response body. Bodies contain everything.
- Exception messages. An ORM error message includes the field value that caused the constraint violation.
- HTTP headers. Authorization, Cookie, Set-Cookie. Logged by default by many request loggers.
- URL query parameters. Tokens, session IDs, sometimes emails passed as
?email=foo@example.com. - Third-party SDK logs. Stripe, Twilio, and many others log payloads in dev mode that should never reach production.
Each is a defensible line of code in isolation. Together they produce log streams that should not exist.
Defense in Depth
No single control catches all of these. A combination of three layers works.
Layer 1 — Source-side redaction. Don't write the PII to the log in the first place. The cleanest defense, and the hardest to enforce systematically.
Layer 2 — Pipeline-level redaction. A log shipper (Fluent Bit, Vector, OTel Collector) strips known-sensitive fields before logs leave the host.
Layer 3 — Backend-side audits. Periodic scans of the log backend for patterns that look like PII. Used to catch what layers 1 and 2 missed.
Most teams skip layers 2 and 3 and rely on developer discipline. This works until it doesn't.
Layer 1: Logging Library Defaults
The simplest way to keep PII out of logs is to make the logger itself reject it. Two patterns work.
Structured logging only. Forbid free-form string interpolation. Every log call is a structured record with named fields. A code review enforces "no email values in fields named message."
// not allowed
$logger->info("User updated: $email at $time");
// required
$logger->info('user.updated', ['user_id' => $userId, 'at' => $time]);
Field-name allowlists or denylists. The logger redacts any field with a name matching a sensitive pattern. email, password, token, card_number, ssn. The redaction happens in the logger before the message is serialized.
class RedactingFilter(logging.Filter):
SENSITIVE = re.compile(r'(email|password|token|secret|card|ssn)', re.I)
def filter(self, record):
if hasattr(record, 'extra'):
for k in record.extra:
if self.SENSITIVE.search(k):
record.extra[k] = '[REDACTED]'
return True
The combination of structured logging plus field-name redaction catches the most common direct-logging failure modes. It does not catch values that get embedded in messages or stack traces, which is where the next layers come in.
Layer 2: Pipeline Redaction
Log shippers can transform records before they leave the host. Vector and Fluent Bit both support pattern-based redaction.
A Vector transform that catches email patterns and card-number patterns:
[transforms.redact_pii]
type = "remap"
inputs = ["raw_logs"]
source = '''
.message = replace(.message, r'[\w.+-]+@[\w-]+\.[\w.-]+', "[EMAIL_REDACTED]")
.message = replace(.message, r'\b(?:\d[ -]*?){13,16}\b', "[CARD_REDACTED]")
'''
Pattern-based redaction is imperfect — it has false positives (every 13-16 digit number gets redacted) and false negatives (different formats slip through). But it catches the common cases without requiring application-side changes, and the cost of running it is negligible.
The place to run this transform is on the host or sidecar, before logs leave the application's process. Redacting at the backend means the PII still traveled across the network and might be on the wire taps. Redact early.
Layer 3: Backend Audits
A periodic scan of the log backend catches what the first two layers miss. Run weekly:
logcli query '{job="production"} |~ "[\\w.+-]+@[\\w-]+\\.[\\w.-]+"'
Look for emails, card-number-shaped strings, common token formats (Stripe sk_*, AWS access keys AKIA*). Each hit is a finding to investigate and a place to add source-side or pipeline-side redaction.
This is not a control that prevents PII from being logged. It is a control that surfaces what got through, so the leak gets closed and the existing data gets retroactively redacted or deleted.
Log backends increasingly support delete operations — Loki, Elasticsearch — but not all. Verify your delete capability before a real finding lands.
Specific Fields and Categories
A few categories deserve specific treatment.
Authentication tokens, API keys, session IDs. Never log these, even redacted. The pattern of "this token existed and was used at this time" can still be enough to enable session-replay attacks or token enumeration.
Payment data. PCI-DSS forbids logging full card numbers and forbids most logging of card data even when masked. Use the payment provider's tokenized references; never log raw card data, even in error paths.
Personally identifying numbers. SSN, passport numbers, national IDs. Treat like card data — never log, even masked.
Email and phone. Less restrictive than card data but typically still subject to GDPR and similar. Redact unless there is a documented audit or compliance reason to retain.
Names and addresses. PII under GDPR. Most logging cases do not need them. If a log line was going to identify a user, log the user ID instead.
URLs and Query Parameters
A frequently overlooked source: URL query parameters. A login flow that does GET /confirm?token=abc123 and an access log that captures the full URL has just persisted a session token. Same for ?email=..., ?reset_token=..., etc.
Strip query parameters at the access-log level by default. Allow them on a per-route basis with explicit configuration. Most reverse proxies (nginx, Caddy, Envoy) support this.
Vendor Concerns
If the log backend is a SaaS vendor (Datadog, Splunk Cloud, Logz.io), your data resides on their infrastructure. Two implications:
- Data Processing Agreements. Verify the vendor's DPA covers the categories of data you might inadvertently send. "We never log PII" is not a defense to a regulator if PII shows up.
- Geographic residency. GDPR cares where the data lives. Vendor regions matter; default routing might not match what your privacy policy promises.
For heavily regulated environments, the answer is often self-hosted log infrastructure for the most sensitive data, with operational logs on the vendor. The split adds complexity but resolves the DPA conversation.
Auditing the Audit
The last control: have someone outside the team that wrote the logging code review what is being logged. The team that wrote the logger has a blind spot for what looks sensitive. A fresh set of eyes — security team, privacy team, compliance officer — finds patterns the original team did not flag.
A quarterly review:
- Run the backend audit queries against a representative time window.
- Sample a random selection of high-volume log streams. Eyeball them.
- Document findings and remediations.
- Update redaction rules based on the findings.
This is a one-day exercise per quarter that consistently surfaces PII that the engineering team did not realize was being logged.
A Day-One Setup
For a service starting from no PII controls:
- Configure the logging library with structured logging required and a denylist of obvious field names.
- Add Vector or OTel Collector pipeline redaction for email and card-number patterns.
- Strip query parameters from access logs by default.
- Add a weekly cron job that searches the log backend for common PII patterns and posts findings to a channel.
- Document the policy. Make it part of code review.
This is a single sprint of work and dramatically reduces ongoing exposure. The cost of getting it wrong is high enough that the investment usually pays off the first time a regulator or auditor asks.
Making sure your observability pipeline doesn't become a compliance problem? We help teams build PII-safe logging without taking away developer productivity. scopeforged.com