IC Improve Code Recipes

Recipe 4.4 · C#

What to Log and What Never to Log

Problem

Logs get two kinds of wrong. Some say too little: "Error" with no context. Others say far too much: full request bodies with passwords, card numbers and session tokens, copied to a file share that half the company can read and kept for seven years. The second kind turns a debugging aid into a data breach.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: the password, the token and the whole DTO end up on disk.
Logger.Write("Login attempt: " + JsonConvert.SerializeObject(request));
Logger.Write("Calling API with token " + accessToken);
Logger.Write("Connecting to " + connectionString);

The improved recipe

Decide on purpose what goes in. Log identifiers and outcomes, not payloads, and mask what you must include. A small masking helper keeps the habit easy.

C#
using System;

namespace ImproveCode.Logging;

public static class LogMask
{
    private const string Redacted = "[REDACTED]";

    // jane.doe@example.com -> j***@example.com
    public static string Email(string? email)
    {
        if (string.IsNullOrWhiteSpace(email))
        {
            return string.Empty;
        }

        int at = email.IndexOf('@');
        return at <= 0
            ? Redacted
            : string.Concat(email.AsSpan(0, 1), "***", email.AsSpan(at));
    }

    // 4111111111111111 -> ************1111
    public static string LastFour(string? value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return string.Empty;
        }

        if (value.Length <= 4)
        {
            return new string('*', value.Length);
        }

        return string.Concat(
            new string('*', value.Length - 4),
            value.AsSpan(value.Length - 4));
    }

    // For values that must never appear, even partially.
    public static string Secret(string? value) =>
        string.IsNullOrEmpty(value) ? string.Empty : Redacted;
}

Usage:

C#
logger.LogInformation(
    "Login succeeded for {UserId} ({Email})",
    user.Id, LogMask.Email(user.Email));

logger.LogWarning(
    "Card {Card} declined for order {OrderId}: {Reason}",
    LogMask.LastFour(card.Number), order.Id, result.Reason);

How it works

The helper is trivial on purpose. The value is in the rule it supports: sensitive data goes through a mask or doesn't go in at all. Code reviewers can search for LogMask and for log calls that pass whole objects.

Here is the checklist I give teams.

Always log Never log
Record IDs, user IDs Passwords, PINs, answers
Operation and outcome Tokens, API keys, cookies
Elapsed time, counts Connection strings
Exceptions with stack Full card numbers, SSNs
Correlation ID Full request or response bodies
Config version at startup Health or financial detail

Log the start and end of every significant operation with its key ID and elapsed time. When an operation fails, log the exception once, at the place where it is handled, with the context needed to reproduce it. Logging the same exception at every layer on the way up produces five copies and makes the log look five times worse than it is.

Variations and pitfalls

  • Be careful with Serilog's {@Object} destructuring and with any logger that serializes whole objects. A LoginRequest record serialized "just for debugging" logs its Password property. Log the fields you need by name instead.
  • Personal data rules (GDPR, CCPA, HIPAA) apply to logs. Shorter retention and masked values make a deletion request or an audit far less painful.
  • For larger systems, look at Microsoft.Extensions.Compliance.Redaction, which lets you tag properties with data classifications and redact them centrally in the logging pipeline.
  • Exceptions can carry secrets too. A SqlException message may include parameter values, and some HTTP client exceptions include the full URL with a query-string token. Don't put secrets in URLs in the first place.
  • Never log at Information inside a tight loop. One line per batch with a count is enough.