Logging is essential for diagnosing production issues — but it's also one of the most common ways PII (Personally Identifiable Information) accidentally ends up in your infrastructure. An email address slips into an exception message. A credit card number gets logged as part of a payment payload. A phone number ends up in a request trace.
Under GDPR, HIPAA, and PCI-DSS, this is not just a code smell — it's a compliance violation. And the fix should not require you to manually audit every _logger.LogInformation() call in your codebase.
💡 SinkSharp's WithPiiMasking() enricher automatically redacts emails, credit card numbers, SSNs, and phone numbers from every log event — before any sink writes. One line of config, zero changes to your existing logging calls.
The Problem with PII in Logs
Consider this log statement from SinkSharp's own WebAPI sample — perfectly reasonable in context:
app.MapPost("/orders", (ILogger<Program> logger) =>
{
logger.LogInformation("Creating new order for user {Email}", "buyer@example.com");
// Without PII masking → "buyer@example.com" written to every sink
// With WithPiiMasking() → "buyer@***.***" reaches the sink
return Results.Created("/orders/42", new { Id = 42, Status = "Pending" });
});Without masking, that email is now sitting in your log file, your dashboard, your Azure Monitor workspace — everywhere your sinks write. If any of those are breached or audited, you have a problem. The same applies to the console sample which logs:
if (batch % 7 == 0)
logger.Log(LogLevel.Error,
"Failed to save batch {Batch} result for user {Email}",
batch, "ops@example.com");
// → PII masked: "ops@***.***"How SinkSharp Masks PII — The Pipeline
SinkSharp's LogPipeline processes every log event in a strict sequence on a background thread. PII masking happens at two points — both before any sink sees the data:
// Step 1 — Enrich: PiiMaskingEnricher.Enrich() runs here
// → masks all string property values in logEvent.Properties
foreach (var enricher in _enrichers)
enricher.Enrich(logEvent, bag);
// Step 2 — Format: renders the message template
logEvent.RenderedMessage = _formatter.Format(logEvent);
// Step 3 — Mask rendered message (catches PII in template literals)
if (_hasPiiMasking && logEvent.RenderedMessage.Length > 0)
logEvent.RenderedMessage = PiiMaskingEnricher.Mask(logEvent.RenderedMessage);
// Step 4 — Route to sinks (sinks only ever see masked data)
await _sinks[0].EmitAsync(logEvent, ct);The two-stage approach is deliberate. Stage 1 masks structured properties — so {Email}, {CardNumber} etc. are redacted before formatting. Stage 3 masks the fully rendered message — catching any PII embedded directly in template string literals.
What Gets Masked — The Actual Regex Rules
SinkSharp's PiiMaskingEnricher applies four compiled regex patterns in sequence:
| Type | Pattern | Example input | Masked output |
|---|---|---|---|
\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b | buyer@example.com | ***@***.*** | |
| Credit card | \b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b | 4111-1111-1111-1111 | ****-****-****-**** |
| SSN | \b\d{3}-\d{2}-\d{4}\b | 123-45-6789 | ***-**-**** |
| Phone | \b(\+?1[-.s]?)?\(?\d{3}\)?[-.s]?\d{3}[-.s]?\d{4}\b | +1-555-867-5309 | ***-***-**** |
All four patterns are RegexOptions.Compiled — they are compiled once at startup and reused, so per-event cost is minimal. The masking runs on the background drainer thread, not the caller thread, so your hot path allocation stays at 92 bytes.
Setup — Console App
For a console app with no DI, use SinkSharpBuilder directly:
var builder = SinkSharpBuilder
.Create()
.MinimumLevel(LogLevel.Debug)
.WithCorrelationId()
.WithEnvironment("MyApp", "Production")
.WithPiiMasking() // ← add this, done
.WriteTo(new ColoredConsoleSink())
.WriteTo(new RollingFileSink("logs", "MyApp"));
var logger = builder.BuildLogger("MyApp.OrderService");Setup — ASP.NET Core / Web API
For ASP.NET Core, use AddSinkSharp() or AddSinkSharpWithHealth() in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSinkSharpWithHealth(options => options
.MinimumLevel(LogLevel.Information)
.MinimumLevelFor("Microsoft", LogLevel.Warning)
.MinimumLevelFor("System.Net", LogLevel.Error)
.WithCorrelationId()
.WithEnvironment(builder.Environment.ApplicationName,
builder.Environment.EnvironmentName)
.WithPiiMasking() // ← one line covers the entire pipeline
.WriteTo(new ColoredConsoleSink())
.WriteTo(new RollingFileSink("logs", "SinkSharp.WebApi")));
var app = builder.Build();
// One-line correlation middleware (Web API / Minimal API)
// Reads X-Correlation-Id header, generates if missing,
// sets AsyncLocal, writes ID back in response header.
app.UseSinkSharp();That's the complete setup. Every ILogger<T> injected anywhere in your app will now have PII masking applied automatically — no changes to your existing controllers, services, or middleware.
How Serilog Destructuring Policies Compare
Serilog does offer three ways to control how data is serialized — and it's worth being precise about what each one can and can't do for PII masking.
What Serilog destructuring can do
ByTransforming<T> lets you reshape a specific type before it's logged. IDestructuringPolicy lets you write conditional masking logic per type — for example, replacing a UserAccount.Password with "******". These work well when your PII lives inside a known typed object:
public class SensitiveDataPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value,
ILogEventPropertyValueFactory factory,
out ILogEventPropertyValue result)
{
if (value is UserAccount user)
{
var anon = new { user.Username, Password = "******" };
result = factory.CreatePropertyValue(anon, deep: true);
return true;
}
result = null;
return false;
}
}Where destructuring policies fall short for PII
Destructuring policies are type-scoped — they fire only when Serilog destructures a known complex object. They do not apply to raw string values. This means the two most common PII leaks in practice are not covered:
1. Plain string properties. If user.Email is a string, no destructuring policy ever fires on it. The value passes directly into the log event as a scalar string — no opportunity to intercept it.
// Email is a string — IDestructuringPolicy never fires
logger.LogInformation("Creating order for {Email}", user.Email);
// Card number is a string — same problem
logger.LogInformation("Payment captured, card {CardNumber}", payment.CardNumber);2. The rendered message string. Even when destructuring masks a property value, the rendered message — the final human-readable string like "Creating order for buyer@example.com" — is assembled after destructuring. Serilog has no built-in mechanism to mask PII in the rendered message. It would require a custom sink wrapper around every sink you register.
3. One policy class per type, registered manually. You need a separate IDestructuringPolicy for each sensitive type — and each one must be registered in your LoggerConfiguration. In a large codebase with many domain types carrying PII, this doesn't scale.
| Approach | Masks typed object properties | Masks plain string values | Masks rendered message | Zero code changes |
|---|---|---|---|---|
Serilog IDestructuringPolicy | ✓ per type | ✗ | ✗ | ✗ policy per type |
Serilog ByTransforming<T> | ✓ per type | ✗ | ✗ | ✗ per type |
| Manual redaction at call site | ✓ | ✓ | ✓ | ✗ every call site |
SinkSharp WithPiiMasking() | ✓ | ✓ | ✓ | ✓ |
Serilog's destructuring policies are genuinely useful for shaping how complex objects appear in structured logs — they're not the wrong tool in general. They're the wrong tool specifically for PII masking, because PII doesn't always live in typed objects and always ends up in the rendered message string.
Compliance Implications
PII masking in logs directly addresses requirements across the main compliance frameworks:
- GDPR Article 5(1)(f) — integrity and confidentiality of personal data. Log files containing PII are in scope.
- PCI-DSS Requirement 3.4 — primary account numbers (PANs) must be rendered unreadable wherever stored, including log files.
- HIPAA § 164.312(b) — audit controls must not inadvertently expose PHI in log outputs.
⚠️ Important: PII masking in logs is a necessary control but not sufficient on its own. You still need access controls on log storage, retention policies, and encrypted transport to your sinks. Masking reduces the blast radius of a log breach — it does not replace a full data protection strategy.
Summary
- PII in logs is a compliance risk that manual code review cannot catch at scale
- SinkSharp's
PiiMaskingEnrichermasks both structured properties and the rendered message — before any sink writes - Four compiled regex patterns cover email, credit card, SSN, and phone out of the box
- One call —
.WithPiiMasking()— inProgram.cscovers your entire app - Masking runs on the background drainer thread — zero impact on your hot path
Try SinkSharp in your project
Drop-in ILogger replacement with PII masking, correlation propagation, and a free real-time dashboard.