Claude Code for logging: Standard Logging in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for logging: Standard Logging in Python
AI

Claude Code for logging: Standard Logging in Python

Published: June 26, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s logging stdlib is the standard structured logging foundation. import logging. basicConfig: logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(name)s: %(message)s"). Logger: log = logging.getLogger(__name__). log levels: log.debug/info/warning/error/critical("msg"). exception: log.exception("error occurred") — includes traceback. extra: log.info("user login", extra={"user_id": uid}). Lazy: log.debug("result: %s", expensive_fn()) — use % not f-string. StreamHandler: h = logging.StreamHandler(); h.setLevel(logging.DEBUG). FileHandler: h = logging.FileHandler("app.log"). RotatingFileHandler: from logging.handlers import RotatingFileHandler; h = RotatingFileHandler("app.log", maxBytes=10*1024*1024, backupCount=5). TimedRotating: from logging.handlers import TimedRotatingFileHandler; h = TimedRotatingFileHandler("app.log", when="midnight", backupCount=30). Formatter: fmt = logging.Formatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s"). setFormatter: h.setFormatter(fmt). addHandler: log.addHandler(h). propagate: log.propagate = False — stop bubbling to root. dictConfig: logging.config.dictConfig(config_dict). fileConfig: logging.config.fileConfig("logging.ini"). Filter: subclass with filter(record) -> bool. LoggerAdapter: adapter = logging.LoggerAdapter(log, {"request_id": rid}). captureWarnings: logging.captureWarnings(True). QueueHandler: async logging to avoid blocking I/O. Claude Code generates logging configurations, JSON formatters, rotating handlers, and request-context adapters.

CLAUDE.md for logging

## logging Stack
- Stdlib: import logging | log = logging.getLogger(__name__)
- Setup: setup_logging(level="INFO", json=True) in app entry point
- Use: log.info("msg") | log.error("msg", exc_info=True) | log.debug("val: %s", val)
- Never: log.debug(f"val: {expensive_fn()}")  # always use % lazy formatting
- JSON: custom Formatter that outputs json.dumps(record_dict) per line
- Rotate: RotatingFileHandler(path, maxBytes=10MB, backupCount=5)

logging Configuration Pipeline

# app/log_config.py — logging setup, JSON formatter, rotating handler, context adapter
from __future__ import annotations

import json
import logging
import logging.config
import logging.handlers
import os
import sys
import traceback
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

# ── Context variable for request-scoped log fields ────────────────────────────
_log_context: ContextVar[dict] = ContextVar("log_context", default={})


# ─────────────────────────────────────────────────────────────────────────────
# 1. JSON formatter
# ─────────────────────────────────────────────────────────────────────────────

class JsonFormatter(logging.Formatter):
    """
    Emit a single JSON object per log line.
    Includes timestamp, level, logger name, message, and any extra fields.
    Context vars from _log_context are merged automatically.

    Example output:
        {"ts":"2024-01-15T10:30:00.123Z","level":"INFO","logger":"app","msg":"user login","user_id":42}
    """

    RESERVED = frozenset(logging.LogRecord(
        "n", 0, "p", 0, "", [], None
    ).__dict__.keys())

    def format(self, record: logging.LogRecord) -> str:
        log_dict: dict[str, Any] = {
            "ts":     self.formatTime(record, self.datefmt or "%Y-%m-%dT%H:%M:%S.%f"),
            "level":  record.levelname,
            "logger": record.name,
            "msg":    record.getMessage(),
        }

        # Merge thread-local context
        log_dict.update(_log_context.get({}))

        # Extra fields passed via extra={} parameter
        for key, val in record.__dict__.items():
            if key not in self.RESERVED and not key.startswith("_"):
                log_dict[key] = val

        # Exception info
        if record.exc_info:
            log_dict["exc"] = self.formatException(record.exc_info)
        if record.stack_info:
            log_dict["stack"] = self.formatStack(record.stack_info)

        return json.dumps(log_dict, default=str)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Setup helpers
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class LogConfig:
    level:           str  = "INFO"
    json:            bool = False
    console:         bool = True
    file:            str | None = None
    max_bytes:       int  = 10 * 1024 * 1024   # 10 MB
    backup_count:    int  = 5
    third_party_level: str = "WARNING"
    capture_warnings: bool = True


def setup_logging(cfg: LogConfig | None = None, **kwargs) -> None:
    """
    Configure root logger with console and/or file handlers.
    Call once at application startup.

    Example:
        setup_logging(LogConfig(level="DEBUG", json=True, file="logs/app.log"))
        setup_logging(level="INFO", json=True)   # via kwargs
    """
    if cfg is None:
        cfg = LogConfig(**{k: v for k, v in kwargs.items() if hasattr(LogConfig, k)})

    root = logging.getLogger()
    root.setLevel(cfg.level)

    # Remove any existing handlers
    root.handlers.clear()

    if cfg.json:
        formatter: logging.Formatter = JsonFormatter()
    else:
        formatter = logging.Formatter(
            "%(asctime)s %(levelname)-8s %(name)-30s %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
        )

    if cfg.console:
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(formatter)
        root.addHandler(handler)

    if cfg.file:
        log_path = Path(cfg.file)
        log_path.parent.mkdir(parents=True, exist_ok=True)
        file_handler = logging.handlers.RotatingFileHandler(
            str(log_path),
            maxBytes=cfg.max_bytes,
            backupCount=cfg.backup_count,
            encoding="utf-8",
        )
        file_handler.setFormatter(formatter)
        root.addHandler(file_handler)

    # Quiet noisy third-party loggers
    for noisy in ("urllib3", "boto3", "botocore", "httpcore", "httpx", "asyncio"):
        logging.getLogger(noisy).setLevel(cfg.third_party_level)

    if cfg.capture_warnings:
        logging.captureWarnings(True)


def setup_logging_from_env() -> None:
    """
    Setup logging from environment variables.
    LOG_LEVEL, LOG_JSON, LOG_FILE.

    Example:
        LOG_LEVEL=DEBUG LOG_JSON=true LOG_FILE=logs/app.log python app.py
    """
    cfg = LogConfig(
        level=os.getenv("LOG_LEVEL", "INFO").upper(),
        json=os.getenv("LOG_JSON", "false").lower() in ("1", "true", "yes"),
        file=os.getenv("LOG_FILE"),
    )
    setup_logging(cfg)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Context adapter
# ─────────────────────────────────────────────────────────────────────────────

class ContextLogger(logging.LoggerAdapter):
    """
    Logger adapter that merges a static context dict into every record.

    Example:
        request_log = ContextLogger(log, {"request_id": req_id, "user_id": user.id})
        request_log.info("Processing started")
        # Emits: ... request_id=abc123 user_id=42 Processing started
    """

    def process(self, msg: str, kwargs: dict) -> tuple[str, dict]:
        extra = {**self.extra, **kwargs.pop("extra", {})}
        kwargs["extra"] = extra
        return msg, kwargs


@contextmanager
def log_context(**fields):
    """
    Add fields to all log records within the context.
    Thread-safe via contextvars.

    Example:
        with log_context(request_id="abc123", user_id=42):
            log.info("Starting request")   # includes request_id + user_id
            do_work()
            log.info("Done")
    """
    token = _log_context.set({**_log_context.get({}), **fields})
    try:
        yield
    finally:
        _log_context.reset(token)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Per-module logger factory
# ─────────────────────────────────────────────────────────────────────────────

def get_logger(name: str, context: dict | None = None) -> logging.Logger | ContextLogger:
    """
    Get a logger; wraps in ContextLogger if context is provided.

    Example:
        log = get_logger(__name__)
        log = get_logger(__name__, context={"service": "payments"})
    """
    logger = logging.getLogger(name)
    if context:
        return ContextLogger(logger, context)
    return logger


# ─────────────────────────────────────────────────────────────────────────────
# 5. dictConfig helper
# ─────────────────────────────────────────────────────────────────────────────

def dictconfig_for_app(
    app_name: str,
    log_level: str = "INFO",
    json: bool = False,
    log_file: str | None = None,
) -> dict:
    """
    Return a logging dictConfig for use with logging.config.dictConfig().

    Example:
        logging.config.dictConfig(dictconfig_for_app("myapp", log_level="DEBUG", json=True))
    """
    formatter_class = f"{JsonFormatter.__module__}.JsonFormatter" if json else "logging.Formatter"
    formatter_fmt = None if json else "%(asctime)s %(levelname)-8s %(name)s: %(message)s"

    handlers = {
        "console": {
            "class":     "logging.StreamHandler",
            "stream":    "ext://sys.stdout",
            "formatter": "default",
        }
    }
    if log_file:
        handlers["file"] = {
            "class":       "logging.handlers.RotatingFileHandler",
            "filename":    log_file,
            "maxBytes":    10 * 1024 * 1024,
            "backupCount": 5,
            "encoding":    "utf-8",
            "formatter":   "default",
        }

    config: dict = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {
                "()": formatter_class,
                **({"format": formatter_fmt} if formatter_fmt else {}),
            }
        },
        "handlers": handlers,
        "loggers": {
            app_name: {
                "level":     log_level,
                "handlers":  list(handlers.keys()),
                "propagate": False,
            }
        },
        "root": {
            "level":    "WARNING",
            "handlers": ["console"],
        },
    }
    return config


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import io

    print("=== logging demo ===")

    # 1. Text format
    setup_logging(LogConfig(level="DEBUG", json=False, console=True))
    log = logging.getLogger("demo")
    log.debug("debug message")
    log.info("info message")
    log.warning("warning message")

    print()

    # 2. JSON format (capture to string for display)
    buf = io.StringIO()
    root = logging.getLogger()
    root.handlers.clear()
    h = logging.StreamHandler(buf)
    h.setFormatter(JsonFormatter())
    root.addHandler(h)

    with log_context(request_id="req-abc123", user_id=42):
        log.info("Processing order", extra={"order_id": 999, "amount": 49.99})
        try:
            1 / 0
        except ZeroDivisionError:
            log.exception("Unexpected error during processing")

    print("JSON log lines:")
    for line in buf.getvalue().splitlines():
        parsed = json.loads(line)
        print(f"  level={parsed['level']:8s} msg={parsed['msg']!r}"
              f" request_id={parsed.get('request_id','?')} "
              f"{'exc=...' if 'exc' in parsed else ''}")

    # 3. ContextLogger
    root.handlers.clear()
    setup_logging(LogConfig(level="INFO", json=False, console=True))
    svc_log = ContextLogger(logging.getLogger("service"), {"component": "payments"})
    svc_log.info("Payment processed", extra={"payment_id": "pay_123"})

    print("\n=== done ===")

For the loguru alternative — loguru provides a single pre-configured logger object with color output, automatic exception formatting, rotation/compression in one call, and decorator-based function tracing — no manual handler/formatter setup required; Python’s stdlib logging requires explicit handler, formatter, and level configuration but is universally available, integrates with all third-party tools, and lets you use logging.getLogger(__name__) across every module without importing custom logger instances — use loguru for scripts and personal projects where zero-config beauty matters, stdlib logging for production applications, libraries, and any code that needs to interoperate with Flask, Django, FastAPI, Celery, and other frameworks that hook into the logging hierarchy. For the structlog alternative — structlog is a third-party structured logging library that processes log events through a pipeline of processors (JSON serialization, timestamp injection, exception formatting), supports both stdlib logging and standalone operation, and makes adding key-value context via log.bind(key=val) natural; stdlib logging uses extra={} for ad-hoc fields — use structlog when structured, context-bound logging is a first-class concern (distributed systems, event-driven apps), stdlib logging when you need universal compatibility and the JsonFormatter pattern above is sufficient. The Claude Skills 360 bundle includes logging skill sets covering JsonFormatter, LogConfig/setup_logging()/setup_logging_from_env(), ContextLogger adapter, log_context() contextvar-based request scoping, get_logger() factory, and dictconfig_for_app() production configuration. Start with the free tier to try logging configuration and structured observability code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free