IC Improve Code Recipes

Recipe 4.4 · Python

What to Log and What Never to Log

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

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.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Logging passwords, tokens and whole request objects (p089_r4_4_logging_secrets_and_dtos_before.py)
"""Logging passwords, tokens and whole request objects

Source: ImproveCode, Chapter 4, Recipe 4.4 "What to Log and What Never to Log"
Section: The way it's often written
Book page: 89  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
json.dumps(vars(...)) replaces JsonConvert.SerializeObject; fragment wrapped in a function.
"""

from __future__ import annotations

import json
from typing import Any


def log_login(logger: Any, request: Any, access_token: str, connection_string: str) -> None:
    # Not this: the password, the token and the whole DTO end up on disk.
    logger.write("Login attempt: " + json.dumps(vars(request)))
    logger.write("Calling API with token " + access_token)
    logger.write("Connecting to " + connection_string)

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.

Usage:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Masking helpers for emails, card numbers and secrets in logs (p089_r4_4_log_masking_helpers.py)
"""Masking helpers for emails, card numbers and secrets in logs

Source: ImproveCode, Chapter 4, Recipe 4.4 "What to Log and What Never to Log"
Section: The improved recipe
Book page: 89-90  -- original C# listing
Converted from C# to Python.
Plain string slicing replaces the C# span-based concatenation; static class becomes
a class of static methods.
"""

from __future__ import annotations


class LogMask:
    _REDACTED = "[REDACTED]"

    # jane.doe@example.com -> j***@example.com
    @staticmethod
    def email(email: str | None) -> str:
        if email is None or not email.strip():
            return ""

        at = email.find("@")
        return LogMask._REDACTED if at <= 0 else email[0] + "***" + email[at:]

    # 4111111111111111 -> ************1111
    @staticmethod
    def last_four(value: str | None) -> str:
        if not value:
            return ""

        if len(value) <= 4:
            return "*" * len(value)

        return "*" * (len(value) - 4) + value[-4:]

    # For values that must never appear, even partially.
    @staticmethod
    def secret(value: str | None) -> str:
        return "" if not value else LogMask._REDACTED

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Logging login and card events with masked values (p090_r4_4_masked_login_and_card_logging.py)
"""Logging login and card events with masked values

Source: ImproveCode, Chapter 4, Recipe 4.4 "What to Log and What Never to Log"
Section: The improved recipe
Book page: 90  -- original C# listing
Converted from C# to Python.
logging module replaces ILogger; LogMask is the class from p089_r4_4_log_masking_helpers.py
(passed in so this fragment stays self-contained).
"""

from __future__ import annotations

import logging
from typing import Any


def log_events(
    logger: logging.Logger, log_mask: Any, user: Any, card: Any, order: Any, result: Any
) -> None:
    logger.info(
        "Login succeeded for %s (%s)",
        user.id, log_mask.email(user.email))

    logger.warning(
        "Card %s declined for order %s: %s",
        log_mask.last_four(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.