📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you keep personal information and secrets out of your logs in an ASP.NET Core service? Cover what must never be logged, data classification and redaction with Microsoft.Extensions.Compliance.Redaction, HTTP logging, and what the Privacy Act (APP 11) means for log retention and breaches.

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.

Senior Security Advanced aspnet-core logging pii privacy-act redaction security

🎯 Key points

  • Never log secrets: passwords, tokens, Authorization headers, connection strings, API keys, card numbers (PCI DSS)
  • Personal information (names, emails, addresses, Medicare or TFNs) is covered by the Privacy Act; logs are a store of it
  • Log identifiers (CustomerId) in structured properties instead of personal data; never log whole request bodies or DTOs
  • Microsoft.Extensions.Compliance.Redaction: classify data with DataClassificationAttribute subclasses, AddRedaction maps classifications to redactors, builder.Logging.EnableRedaction applies them
  • Works with [LoggerMessage] parameters and [LogProperties] objects; HMAC redactor gives stable pseudonyms so you can still correlate
  • HTTP logging: allowlist headers (others show [Redacted]), never log bodies on auth or payment endpoints
  • APP 11: take reasonable steps to protect personal information; APP 11.2: destroy or de-identify when no longer needed, so set log retention
  • Verify continuously (leak tests, scheduled KQL scans, access audits) and have an incident plan: a leaked log store can be an eligible data breach under the NDB scheme, with OAIC notification and reputational cost

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, Authorization or 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."


What goes where

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

Controls in layers

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate treats logs as a sensitive data store and can enforce privacy in code, with awareness of Australian obligations.

Green flags

  • Lists secrets and personal information that must not be logged and logs identifiers instead.
  • Knows the redaction library's classify, register, enable flow and its limits.
  • Uses header allowlists and avoids body logging on sensitive endpoints.
  • Connects retention and breach handling to APP 11, APP 11.2 and the NDB scheme.

Red flags

  • "We mask it in the UI" as the only control.
  • Logs full requests for debugging in production.
  • Unaware that logs fall under privacy law.

📚 Learn in depth

1. Why logs leak

  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.

2. How the redaction library works

Packages: Microsoft.Extensions.Compliance.Redaction (redactors) and Microsoft.Extensions.Telemetry (logging integration).

  1. Taxonomy: you define DataClassification values (a taxonomy name plus a value), wrapped in attributes deriving from DataClassificationAttribute.
  2. Annotation: put the attributes on [LoggerMessage] parameters, or on properties of a type logged with [LogProperties].
  3. Registration: 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.
  4. Enforcement: 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.

3. HTTP logging

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.

4. The Privacy Act in practice

  • APP 11.1: reasonable steps to protect personal information from misuse, interference, loss and unauthorised access. Logs are included.
  • APP 11.2: destroy or de-identify personal information you no longer need. For logs, that means per-table retention in Log Analytics and not copying logs into long-lived stores.
  • Notifiable Data Breaches scheme: unauthorised access to personal information likely to cause serious harm must be notified to the OAIC and affected individuals. A publicly exposed log store or a leaked workspace key can qualify.
  • The ACSC's guidance on event logging asks for useful security logs, retained centrally and protected; that pushes toward logging security events without logging personal content.

5. Testing for leaks

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.

Try it yourself

  1. Add the redaction packages, classify an Email parameter on a [LoggerMessage] method, and compare console output with and without EnableRedaction().
  2. Switch the redactor to HMAC and confirm the same input always gives the same token.
  3. Turn on AddHttpLogging with default options and send an Authorization header; confirm it appears as [Redacted].
  4. Write a unit test with FakeLogger that fails if a test email appears in any record.
  5. Run a KQL query like traces | where message matches regex @"[\w.+-]+@[\w-]+\.[\w.]+" over the last 30 days in a test workspace.

💻 Code

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]"));
    }
}

⚠ Common mistakes

  • Mistake: Logging whole request models or {@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.
  • Mistake: Assuming 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.
  • Mistake: Leaving EF Core EnableSensitiveDataLogging() on outside Development. Why it is wrong: Parameter values, including personal data, appear in logs. Instead: Enable it only in Development.
  • Mistake: Turning on HTTP logging with request bodies for auth or payment endpoints. Why it is wrong: Passwords and card data are logged. Instead: Headers allowlist only, no bodies, exclude sensitive paths.
  • Mistake: Keeping logs for two years by default. Why it is wrong: APP 11.2 expects personal information to be destroyed or de-identified when no longer needed, and longer retention widens breach impact. Instead: Set retention per table to what operations actually need.
  • Mistake: Using a plain SHA-256 hash of emails as a "pseudonym". Why it is wrong: Unkeyed hashes of guessable values can be reversed with a dictionary. Instead: Use a keyed HMAC with the key in Key Vault.
  • Mistake: Giving every developer read access to production workspaces. Why it is wrong: Logs become a broad access path to personal information. Instead: RBAC, just-in-time access and query auditing.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions classifying properties or logging identifiers instead of data. Why: Checks they understand structured properties, which is what redaction acts on.
    How to answer

    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.

  2. When: Candidate puts a classification attribute on a log method parameter. Why: Checks they know the LoggerMessage generator, which classification attributes plug into.
    How to answer

    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.

  3. When: Candidate mentions an HMAC key or other secret used by the logging pipeline. Why: Checks they know where secrets such as the HMAC key should live.
    How to answer

    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".

🛠 Real-world problems: how you handle them

Customer emails and tokens found in Application Insights
Situation
A customer-facing API for [an Australian retailer] stored telemetry in an Application Insights workspace with [730]-day retention. A penetration test reported customer emails visible in traces, and a developer noticed a bearer token in an exception log.
Signals
Pen-test finding; KQL regex search found about [12,000] email addresses and [40] JWT-shaped strings in 90 days of `traces` and `exceptions`; [35] people had reader access to the workspace.
Investigation
Grouped matches by `customDimensions.CategoryName` and `OriginalFormat`: most came from one global exception handler logging the bound request model, the rest from HTTP logging configured with all request headers in a staging-derived config. Checked access logs on the workspace to judge whether the data had been accessed inappropriately, and briefed the privacy officer to assess whether it was an eligible data breach.
Resolution
Immediate: removed request-model logging and the header setting in a hotfix, purged affected records with the Log Analytics purge API, rotated the exposed tokens' signing keys, and reduced workspace access to on-call engineers. Long term: classified DTO properties, enabled redaction with an HMAC redactor for personal data, and cut retention to [90] days.
Prevention
CI test with `FakeLogger` asserting known test personal data never appears; scheduled KQL scan alerting on email or JWT patterns; HTTP logging allowlist in shared start-up code; privacy review item in the definition of done.

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.

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me