Secure logging: what counts as secrets and personal information, why logs are a breach surface, Microsoft.Extensions.Compliance.Redaction (data classification attributes, AddRedaction, EnableRedaction, erasing and HMAC redactors, [LogProperties]), safe HTTP logging and header allowlists, scanning and testing for leaks, and Australian Privacy Act APP 11, APP 11.2 retention and the Notifiable Data Breaches scheme.
Treat logs as a data store that attackers and too many staff can read. Never log secrets (passwords, tokens, Authorization headers, connection strings, card numbers) and keep personal information out: log identifiers like CustomerId, not names, emails or request bodies.
Enforce it in code rather than by memory: Microsoft.Extensions.Compliance.Redaction lets you classify fields with attributes, map classifications to redactors (erase, or HMAC for a stable pseudonym) with AddRedaction, and apply them to logs with EnableRedaction. Use header allowlists in HTTP logging.
In Australia, APP 11 requires reasonable steps to protect personal information and APP 11.2 requires destroying or de-identifying it when no longer needed, so retention matters, and a leaked log store can be a notifiable data breach. The trade-off: less detail in logs versus a smaller breach surface.
"I start from the threat model: logs get copied to more places and read by more people than the database. They go to Application Insights, to a SIEM, to support staff, sometimes to a vendor. So anything in a log is effectively published inside the company. Secrets never go in: no passwords, bearer tokens,
Authorizationor cookie headers, connection strings or full card numbers. Personal information, names, emails, phone numbers, addresses, Medicare numbers, stays out too; I log the customer id and look the person up in the system of record when I really need to.Rules people have to remember fail, so I make it structural. In .NET there's
Microsoft.Extensions.Compliance.Redaction: I define data classifications, mark properties and[LoggerMessage]parameters with attributes like[PersonalData], and register redactors: an erasing redactor for secrets and an HMAC redactor for personal data, so the same email always becomes the same opaque token and I can still correlate events without seeing the email.EnableRedaction()makes the logging pipeline apply them. HTTP logging gets an explicit header allowlist and no bodies. For example, at [company] we [found customer emails in Application Insights from an exception message that included the request DTO, and fixed it with classification plus a test that fails the build if a classified property is logged unredacted].The Australian angle is the Privacy Act. APP 11 says we must take reasonable steps to protect personal information, including in logs, and APP 11.2 says we destroy or de-identify it once it's no longer needed, which means a deliberate retention period, not 'keep forever'. If a log store with personal data is exposed, that can be an eligible data breach under the Notifiable Data Breaches scheme. The mistake I see is teams setting 730-day retention 'just in case' on logs full of emails. Log less, redact by default, keep it only as long as you need it."
| Data | In logs? | Instead |
|---|---|---|
| Passwords, tokens, API keys, connection strings | Never | Nothing; log that auth failed and why (category) |
Authorization, Cookie, Set-Cookie headers |
Never | Header allowlist |
| Full card numbers (PAN), CVV | Never (PCI DSS) | Last four digits at most, from the gateway's token |
| Names, emails, phone, address, DOB | Avoid | CustomerId; HMAC-redacted value if correlation is needed |
| Government identifiers (TFN, Medicare) | Never | Internal id |
| Order ids, product ids, status codes | Yes | – |
| IP addresses | Case by case (can be personal information) | Truncate or keep short retention |
| Layer | Control |
|---|---|
| Code | Data classification attributes, [LoggerMessage] with classified parameters, no DTO logging |
| Pipeline | EnableRedaction(), HTTP logging allowlists |
| Export | Collector redaction processors, Log Analytics transformations |
| Store | RBAC on workspaces, retention per table, region (Australia East/Southeast) |
| Process | Leak tests in CI, periodic KQL scans for email/token patterns, incident plan for NDB |
A scan of [90] days of traces for email patterns found about [12,000] customer emails, almost all from one exception handler that logged the bound request model. Classifying the model, enabling redaction, and cutting retention from [730] to [90] days removed the exposure and reduced the workspace's stored personal data to zero on the next scan.
Checks whether the candidate treats logs as a sensitive data store and can enforce privacy in code, with awareness of Australian obligations.
Green flags
Red flags
request DTO ──► exception message ("Invalid email [email protected]")
│ │
│ ▼
│ logger.LogError(ex, ...) ──► Application Insights (traces, exceptions)
│ │
└──► logger.LogInformation("{@Request}") ├──► exported to SIEM
├──► copied into support tickets
└──► retained for N days
The common paths are: logging whole objects, exception messages that echo input, HTTP logging with bodies or all headers, EF Core EnableSensitiveDataLogging left on, and SQL parameter values in dependency telemetry.
Packages: Microsoft.Extensions.Compliance.Redaction (redactors) and Microsoft.Extensions.Telemetry (logging integration).
DataClassification values (a taxonomy name plus a value), wrapped in attributes deriving from DataClassificationAttribute.[LoggerMessage] parameters, or on properties of a type logged with [LogProperties].services.AddRedaction(b => b.SetRedactor<ErasingRedactor>(new DataClassificationSet(Secret)) ...) maps classifications to redactors. SetHmacRedactor (marked experimental) produces a keyed hash so equal inputs give equal outputs without being reversible without the key.builder.Logging.EnableRedaction() installs a logger that runs annotated values through the matching redactor before any provider sees them.[LoggerMessage] parameter with [PersonalData]
│
▼
extended logger (EnableRedaction) ──► IRedactorProvider.GetRedactor(PersonalData)
│ │
│ ▼
│ HmacRedactor: "[email protected]" → "9F3A..."
▼
providers (console, OpenTelemetry) receive the redacted value only
Plain logger.LogInformation("... {Email}", email) is not redacted: the library only knows about values whose classification it can see. That is why generated logging plus classification is the pattern.
AddHttpLogging logs headers on an allowlist (RequestHeaders, ResponseHeaders); everything else is written as [Redacted]. Bodies are off unless you add RequestBody/ResponseBody to LoggingFields. Microsoft.AspNetCore.Diagnostics.Middleware adds AddHttpLoggingRedaction to classify route parameters and headers.
Use FakeLogger from Microsoft.Extensions.Diagnostics.Testing to capture log records in tests and assert no known test email or token appears. Schedule a KQL query that searches traces for email and JWT patterns and alerts on any hit.
Email parameter on a [LoggerMessage] method, and compare console output with and without EnableRedaction().AddHttpLogging with default options and send an Authorization header; confirm it appears as [Redacted].FakeLogger that fails if a test email appears in any record.traces | where message matches regex @"[\w.+-]+@[\w-]+\.[\w.]+" over the last 30 days in a test workspace.Classification, redaction and safe HTTP logging.
// Program.cs
// Packages: Microsoft.Extensions.Compliance.Redaction, Microsoft.Extensions.Telemetry
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.Extensions.Compliance.Classification;
using Microsoft.Extensions.Compliance.Redaction;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRedaction(r =>
{
// Secrets: erased completely
r.SetRedactor<ErasingRedactor>(new DataClassificationSet(ShopTaxonomy.Secret));
#pragma warning disable EXTEXP0002 // HMAC redactor is experimental
// Personal data: stable pseudonym so events for the same person still correlate
r.SetHmacRedactor(o =>
{
o.KeyId = 1; // rotate keys by id
o.Key = builder.Configuration["Redaction:HmacKey"]!; // base64 key from Key Vault, never in source
}, new DataClassificationSet(ShopTaxonomy.Personal));
#pragma warning restore EXTEXP0002
});
builder.Logging.EnableRedaction(); // apply redactors before any provider sees values
builder.Services.AddHttpLogging(o =>
{
o.LoggingFields = HttpLoggingFields.RequestPropertiesAndHeaders | HttpLoggingFields.ResponseStatusCode;
o.RequestHeaders.Add("X-Client-Version"); // allowlist; Authorization/Cookie stay [Redacted]
});
var app = builder.Build();
app.UseHttpLogging();
app.MapPost("/customers", (NewCustomer c, ILogger<Program> logger) =>
{
var id = Guid.NewGuid();
logger.CustomerRegistered(id, c.Email); // Email is HMAC-redacted
return TypedResults.Created($"/customers/{id}");
});
app.Run();
public sealed record NewCustomer(string Name, string Email);
public static class ShopTaxonomy
{
public static DataClassification Secret { get; } = new("Shop", nameof(Secret));
public static DataClassification Personal { get; } = new("Shop", nameof(Personal));
}
public sealed class SecretAttribute() : DataClassificationAttribute(ShopTaxonomy.Secret);
public sealed class PersonalDataAttribute() : DataClassificationAttribute(ShopTaxonomy.Personal);
public static partial class CustomerLog
{
[LoggerMessage(EventId = 3001, Level = LogLevel.Information, Message = "Customer {CustomerId} registered with email {Email}")]
public static partial void CustomerRegistered(this ILogger logger, Guid customerId, [PersonalData] string email);
}
A test that fails if personal data leaks (package Microsoft.Extensions.Diagnostics.Testing):
using Microsoft.Extensions.Logging.Testing;
using Xunit;
public sealed class LoggingLeakTests
{
[Fact]
public void Registration_log_does_not_contain_raw_email()
{
var collector = new FakeLogCollector();
var logger = new FakeLogger(collector);
// In a real test, resolve the app's logger via WebApplicationFactory so EnableRedaction is applied
logger.LogInformation("Customer {CustomerId} registered", Guid.NewGuid());
Assert.DoesNotContain(collector.GetSnapshot(), r => r.Message.Contains("[email protected]"));
}
}
{@Request}. Why it is wrong: Every personal field in the model ends up in the log store. Instead: Log identifiers and a few non-sensitive fields.EnableRedaction() redacts every log call. Why it is wrong: It only redacts values whose classification it can see (classified [LoggerMessage] parameters or [LogProperties] objects); plain templates pass through. Instead: Use generated, classified logging for anything sensitive.EnableSensitiveDataLogging() on outside Development. Why it is wrong: Parameter values, including personal data, appear in logs. Instead: Enable it only in Development.I treat log hygiene as a privacy control with the same weight as database encryption, because in breaches logs are often the easier target. The pattern I push is: identifiers by default, classification at the type level, redaction in the pipeline, and a scan that proves it. Pseudonymised values (HMAC) are still personal information under the Privacy Act if they can be re-linked, so they reduce risk rather than remove it.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Log ids only | Default for all services | Lookup needed to see the person | – |
| Erasing redactor | Secrets, data you never need | Lose the value entirely | Need to correlate by the value |
| HMAC redactor | Correlate events for the same person | Key management; still personal information | Low-entropy values without a strong key |
| Collector/workspace redaction | Last line of defence for legacy apps | Regex misses, extra processing | As the only control |
| Short retention | Logs with any personal data | Less history for investigations | Security audit logs with legal retention needs |
Structured logging records an event: a constant message template plus named properties, instead of a pre-built string. In logger.LogInformation("Order {OrderId} placed in {ElapsedMs} ms", id, ms), the provider gets the template and the values separately, so OrderId and ElapsedMs become queryable fields (Application Insights customDimensions, OpenTelemetry attributes, Seq properties).
With string interpolation ($"Order {id} placed") the provider only sees a finished string: no properties, a different message every time, and the string is built even when the level is disabled. Analyser CA2254 warns about this.
The trade-off: templates take discipline in naming, but they turn logs from text you grep into data you can filter, group and alert on.
A normal call like logger.LogDebug("Item {Id} took {Ms}", id, ms) goes through LoggerExtensions: it allocates a params object[], boxes the int and double, and does that even when Debug is off. The [LoggerMessage] source generator turns a partial method into a strongly typed one: it checks IsEnabled first, uses a cached, pre-parsed template, and passes values without boxing, so a filtered call allocates zero bytes and costs close to nothing (around a nanosecond on typical hardware; benchmark on yours, since absolute numbers vary by CPU and runtime). It also checks at compile time that placeholders match parameters.
You still guard with IsEnabled when computing an argument is expensive, because arguments are evaluated before the call.
The trade-off: more code per event, so use it for hot paths, libraries and your main event catalogue, not every one-off line.
User secrets (the Secret Manager) keep developer-only secrets out of the repository. dotnet user-secrets init adds a UserSecretsId to the project file, and dotnet user-secrets set "Stripe:ApiKey" "sk_test_..." writes the value to a plain-text secrets.json in your user profile (%APPDATA%\Microsoft\UserSecrets\<id> on Windows, ~/.microsoft/usersecrets/<id> on Linux and macOS).
CreateBuilder loads them only in the Development environment, as a provider after the appsettings files, so code reads them like any other key.
They are not encryption: anyone or anything running as you can read the file. In production use Azure Key Vault with managed identity, Key Vault references, or platform secrets, and passwordless Entra ID authentication where the service supports it. The trade-off: zero setup for developers, but no protection beyond "not in git".
How to tell it (STAR)
**S:** At [company] a penetration test found customer emails in our Application Insights traces, and we then spotted a bearer token in an exception log, in a workspace with two-year retention and [35] readers. **T:** I led the clean-up and had to stop the leak, limit the exposure and make sure it couldn't recur. **A:** I used KQL to find every source, which came down to an exception handler logging the request model and an over-broad HTTP logging config. We hotfixed both, purged the affected records, rotated keys, narrowed access and involved our privacy officer to assess the breach. Then I introduced data classification with redaction, shorter retention and a CI test and scheduled scan for leaks. **R:** The next scan found [zero] emails or tokens, retention dropped to [90] days, and the scan has since caught [one] new leak before it reached production.
Last updated 23 Nov 2026.