From 6655e36fba162c00e7e3ac9591704f626a27d99c Mon Sep 17 00:00:00 2001 From: Jason Antman Date: Sat, 21 Nov 2026 08:44:43 -0500 Subject: [PATCH] Add opt-in JSON structured logging via LOG_FORMAT=json (#52) Setting LOG_FORMAT=json makes mac-server write every log record (application, AUTH, library and HTTP access log) to stderr as one JSON object per line: timestamp (ISO 8601 with offset), level, logger, message, remote_addr/url from the Quart request context, exc_info and stack_info when present, filename/lineno/funcName in verbose mode, and any extra= fields (non-serializable values rendered with str()). Implementation is stdlib only: a JsonFormatter next to the existing RequestFormatter, and configure_log_format() called from main(). In JSON mode it leaves Quart's default_handler as the only root handler, because today the root logger has both the basicConfig handler and default_handler and every record is printed twice; reusing both would duplicate JSON lines or mix text into the stream. Text mode (the default) is untouched. Unknown LOG_FORMAT values keep text and log a warning rather than preventing startup. Docs: LOG_FORMAT in the configuration env var table plus a JSON Logging section with the field list; CLAUDE.md updated. Spec Kit artifacts in specs/20261121-083531-json-logging/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KQ8DrMX1VdrmZKGbKERH6h --- .specify/feature.json | 2 +- CLAUDE.md | 4 + docs/source/configuration.rst | 40 ++++ .../checklists/requirements.md | 37 ++++ .../contracts/log-record.md | 21 ++ .../data-model.md | 19 ++ specs/20261121-083531-json-logging/plan.md | 61 ++++++ .../quickstart.md | 17 ++ .../20261121-083531-json-logging/research.md | 60 ++++++ specs/20261121-083531-json-logging/spec.md | 143 +++++++++++++ specs/20261121-083531-json-logging/tasks.md | 59 ++++++ src/dm_mac/__init__.py | 76 +++++++ tests/test_init.py | 199 ++++++++++++++++++ 13 files changed, 737 insertions(+), 1 deletion(-) create mode 100644 specs/20261121-083531-json-logging/checklists/requirements.md create mode 100644 specs/20261121-083531-json-logging/contracts/log-record.md create mode 100644 specs/20261121-083531-json-logging/data-model.md create mode 100644 specs/20261121-083531-json-logging/plan.md create mode 100644 specs/20261121-083531-json-logging/quickstart.md create mode 100644 specs/20261121-083531-json-logging/research.md create mode 100644 specs/20261121-083531-json-logging/spec.md create mode 100644 specs/20261121-083531-json-logging/tasks.md diff --git a/.specify/feature.json b/.specify/feature.json index 0e1c681..bc3d5d6 100644 --- a/.specify/feature.json +++ b/.specify/feature.json @@ -1,3 +1,3 @@ { - "feature_directory": "specs/002-second-relay-support" + "feature_directory": "specs/20261121-083531-json-logging" } diff --git a/CLAUDE.md b/CLAUDE.md index 9ac08a7..39387e1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -225,6 +225,8 @@ request context. Custom `RequestFormatter` adds request context (`remote_addr`, `url`) to all logs when available. The `AUTH` logger is used specifically for authentication/authorization decisions. +With `LOG_FORMAT=json`, `configure_log_format()` (called from `main()`) leaves Quart's `default_handler` as the only root handler and gives it `JsonFormatter` (`src/dm_mac/__init__.py`): one JSON object per line with `timestamp`, `level`, `logger`, `message`, `remote_addr`, `url`, optional `exc_info`/`stack_info`, `filename`/`lineno`/`funcName` in verbose mode, and any `extra=` fields. Text mode is untouched (note it currently emits each record twice, via the `basicConfig` handler and `default_handler`). + ## Environment Variables Required for NeonGetter: @@ -242,6 +244,7 @@ Optional for MAC server: - `SLACK_CONTROL_CHANNEL_ID`: Private admin channel ID - `SLACK_OOPS_CHANNEL_ID`: Public channel for oops/maintenance notices - `STATUS_WEBHOOK_URL`: If set, URL to POST status-change webhooks to (see Status-Change Webhook above); disabled when unset +- `LOG_FORMAT`: `text` (default) or `json`; see Logging above. Unknown values keep text and log a warning ## Testing Notes @@ -276,4 +279,5 @@ We have a special process for developing features. When asked to begin work on a For additional context about technologies to be used, project structure, shell commands, and other important information, read the current plan +at specs/20261121-083531-json-logging/plan.md diff --git a/docs/source/configuration.rst b/docs/source/configuration.rst index 17f4a08..bb174b8 100644 --- a/docs/source/configuration.rst +++ b/docs/source/configuration.rst @@ -102,6 +102,46 @@ Environment Variables * - ``STATUS_WEBHOOK_URL`` - no - If set, the URL to POST a JSON status-change webhook to on every meaningful machine event (login, logout, unauthorized or unknown fob, override login, oops, un-oops, lockout, unlock, reboot). Disabled when unset. See :ref:`http-api.status-webhook`. + * - ``LOG_FORMAT`` + - no + - Log output format: ``text`` (default) or ``json`` (case-insensitive). Any other value keeps text output and logs a warning. See :ref:`configuration.json-logging`. + +.. _configuration.json-logging: + +JSON Logging +------------ + +Setting ``LOG_FORMAT=json`` makes the server write every log line (application, ``AUTH``, library and HTTP access logs) to standard error as a single JSON object, for ingestion by a log aggregator. The default text format is unchanged when ``LOG_FORMAT`` is unset. + +.. list-table:: JSON log fields + :header-rows: 1 + + * - Field + - Description + * - ``timestamp`` + - ISO 8601 time with millisecond precision and UTC offset, e.g. ``2026-11-21T08:37:21.462-05:00`` + * - ``level`` + - ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` or ``CRITICAL`` + * - ``logger`` + - Logger name; authentication and authorization decisions use ``AUTH`` + * - ``message`` + - The formatted log message + * - ``remote_addr``, ``url`` + - Client address and request URL when logged while handling an HTTP request, otherwise ``null`` + * - ``exc_info``, ``stack_info`` + - Formatted traceback / stack, only when present + * - ``filename``, ``lineno``, ``funcName`` + - Source location, only in verbose (``-v``) mode + * - *other keys* + - Any fields passed via the logging ``extra`` argument; values that are not JSON-serializable are rendered as strings + +Example: + +.. code-block:: json + + {"timestamp": "2026-11-21T08:37:21.462-05:00", "level": "INFO", "logger": "AUTH", "message": "...", "remote_addr": "10.0.0.5", "url": "http://mac/api/machine/update"} + +For example, ``jq 'select(.logger == "AUTH")'`` selects all authorization decisions. .. _configuration.machine-state-dir: diff --git a/specs/20261121-083531-json-logging/checklists/requirements.md b/specs/20261121-083531-json-logging/checklists/requirements.md new file mode 100644 index 0000000..0084639 --- /dev/null +++ b/specs/20261121-083531-json-logging/checklists/requirements.md @@ -0,0 +1,37 @@ +# Specification Quality Checklist: JSON (Structured) Logging + +**Purpose**: Validate specification completeness and quality before proceeding to planning +**Created**: 2026-11-21 +**Feature**: [spec.md](../spec.md) + +## Content Quality + +- [x] No implementation details (languages, frameworks, APIs) +- [x] Focused on user value and business needs +- [x] Written for non-technical stakeholders +- [x] All mandatory sections completed + +## Requirement Completeness + +- [x] No [NEEDS CLARIFICATION] markers remain +- [x] Requirements are testable and unambiguous +- [x] Success criteria are measurable +- [x] Success criteria are technology-agnostic (no implementation details) +- [x] All acceptance scenarios are defined +- [x] Edge cases are identified +- [x] Scope is clearly bounded +- [x] Dependencies and assumptions identified + +## Feature Readiness + +- [x] All functional requirements have clear acceptance criteria +- [x] User scenarios cover primary flows +- [x] Feature meets measurable outcomes defined in Success Criteria +- [x] No implementation details leak into specification + +## Notes + +- The audience is server administrators, and the feature is itself a log output format, + so the spec names the user-visible contract (field names, ISO 8601 timestamps, an + environment variable, the logging "extra" mechanism). These are the observable + interface, not implementation choices; module and class design is left to the plan. diff --git a/specs/20261121-083531-json-logging/contracts/log-record.md b/specs/20261121-083531-json-logging/contracts/log-record.md new file mode 100644 index 0000000..cf74574 --- /dev/null +++ b/specs/20261121-083531-json-logging/contracts/log-record.md @@ -0,0 +1,21 @@ +# Contract: `LOG_FORMAT` and JSON log lines + +## Configuration + +| `LOG_FORMAT` value | Behaviour | +|--------------------|-----------| +| unset, empty, `text` (any case) | existing text format, unchanged | +| `json` (any case) | one JSON object per line, fields per `data-model.md` | +| anything else | text format, plus one WARNING: `Unknown LOG_FORMAT ''; using text` | + +## Example (normal mode) + +```json +{"timestamp": "2026-11-21T08:37:21.462-05:00", "level": "INFO", "logger": "AUTH", "message": "...", "remote_addr": "10.0.0.5", "url": "http://mac/api/machine/update"} +``` + +## Example (verbose mode, with exception) + +```json +{"timestamp": "...", "level": "ERROR", "logger": "dm_mac.models.machine", "message": "...", "remote_addr": null, "url": null, "filename": "machine.py", "lineno": 123, "funcName": "save_cache", "exc_info": "Traceback (most recent call last):\n ..."} +``` diff --git a/specs/20261121-083531-json-logging/data-model.md b/specs/20261121-083531-json-logging/data-model.md new file mode 100644 index 0000000..3242ec0 --- /dev/null +++ b/specs/20261121-083531-json-logging/data-model.md @@ -0,0 +1,19 @@ +# Data Model: JSON Log Record + +One JSON object per line on standard error. + +| Field | Type | Presence | Source | +|-------|------|----------|--------| +| `timestamp` | string, ISO 8601 with offset, ms precision | always | `record.created` | +| `level` | string (`DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`) | always | `record.levelname` | +| `logger` | string | always | `record.name` | +| `message` | string | always | `record.getMessage()` | +| `remote_addr` | string or null | always | Quart `request.remote_addr` if in request context | +| `url` | string or null | always | Quart `request.url` if in request context | +| `exc_info` | string (formatted traceback) | when record has exception info | `formatException()` | +| `stack_info` | string | when `stack_info=True` | `formatStack()` | +| `filename`, `lineno`, `funcName` | string, int, string | verbose mode only | record attributes | +| *extra keys* | any JSON value; non-serializable values as `str()` | when supplied via `extra=` | `record.__dict__` | + +Validation rules: the line must parse with `json.loads` to a dict; no literal newlines. +Extra keys never override the fixed fields above. diff --git a/specs/20261121-083531-json-logging/plan.md b/specs/20261121-083531-json-logging/plan.md new file mode 100644 index 0000000..2b479c0 --- /dev/null +++ b/specs/20261121-083531-json-logging/plan.md @@ -0,0 +1,61 @@ +# Implementation Plan: JSON (Structured) Logging + +**Branch**: `robot-army/issue-52-json-logging` | **Date**: 2026-11-21 | **Spec**: [spec.md](spec.md) +**Input**: Feature specification from `specs/20261121-083531-json-logging/spec.md` + +## Summary + +Add an opt-in JSON log format to `mac-server`, selected by a new `LOG_FORMAT` +environment variable (`text` default, `json`). A stdlib-only `JsonFormatter` in +`src/dm_mac/__init__.py` renders each record as one JSON line with timestamp, level, +logger, message, request context, exception/stack text, caller `extra` fields, and (in +verbose mode) source location. A `configure_log_format()` helper called from `main()` +applies it. Text mode is untouched. + +## Technical Context + +**Language/Version**: Python 3.13 (per `pyproject.toml`) +**Primary Dependencies**: stdlib `logging`, `json`, `datetime`; Quart (`has_request_context`, `request`, `quart.logging.default_handler`) +**Storage**: N/A +**Testing**: pytest + pytest-asyncio via `nox -s tests` +**Target Platform**: Linux server / Docker image +**Project Type**: web service (single project) +**Performance Goals**: no measurable change; one `json.dumps` per record +**Constraints**: must never raise into callers; text output unchanged when unset +**Scale/Scope**: one module changed, one env var, docs + +## Constitution Check + +*GATE: Must pass before Phase 0 research. Re-checked after Phase 1 design.* + +| Principle | Assessment | +|-----------|------------| +| I. Safety & Reliability | No machine-control logic changes. Formatting errors are caught by `logging.Handler.emit` → `handleError` and never reach callers; `json.dumps(default=str)` prevents serialization errors. Invalid `LOG_FORMAT` falls back to text instead of failing startup. PASS | +| II. Testing Discipline | Unit tests for every field rule, request context, exceptions, extras, location, env selection and fallback. No network. PASS | +| III. Simplicity & YAGNI | Stdlib only, no new dependency (`python-json-logger` rejected). One formatter class, one function, one env var. CLI tools out of scope. PASS | +| IV. Backward Compatibility | Default is text and the text code path is not modified. No API, config file or pickle changes. PASS | +| V. Documentation | `LOG_FORMAT` and field list added to `docs/source/configuration.rst` and `CLAUDE.md`. PASS | +| Operational: Logging | `AUTH` logger and INFO-level state-change logging unchanged; JSON makes `AUTH` filterable by field. PASS | + +Post-design re-check: unchanged, PASS. No complexity tracking entries. + +## Project Structure + +### Documentation (this feature) + +`specs/20261121-083531-json-logging/`: `spec.md`, `plan.md`, `research.md`, +`data-model.md`, `contracts/log-record.md`, `quickstart.md`, `tasks.md`. + +### Source Code (repository root) + +- `src/dm_mac/__init__.py`: `JsonFormatter`, `configure_log_format()`, call from `main()` +- `tests/test_init.py`: new tests; patch `configure_log_format` in existing `main()` tests +- `docs/source/configuration.rst`, `CLAUDE.md`: env var + field docs + +**Structure Decision**: Keep the formatter next to the existing `RequestFormatter` in +`src/dm_mac/__init__.py`, since both depend on Quart's request context and the module's +`default_handler` wiring. No new module. + +## Complexity Tracking + +None. diff --git a/specs/20261121-083531-json-logging/quickstart.md b/specs/20261121-083531-json-logging/quickstart.md new file mode 100644 index 0000000..771667e --- /dev/null +++ b/specs/20261121-083531-json-logging/quickstart.md @@ -0,0 +1,17 @@ +# Quickstart: JSON logging + +```bash +LOG_FORMAT=json poetry run mac-server # JSON, INFO and above +LOG_FORMAT=json poetry run mac-server --verbose # JSON, DEBUG, with file/line/function +poetry run mac-server # unchanged text output +``` + +Docker: add `-e LOG_FORMAT=json` (or `environment: LOG_FORMAT: json` in compose). + +Verify every line is JSON: + +```bash +LOG_FORMAT=json poetry run mac-server 2>&1 >/dev/null | head -5 | python -m json.tool --json-lines +``` + +Filter authorization decisions with `jq`: `jq 'select(.logger == "AUTH")'`. diff --git a/specs/20261121-083531-json-logging/research.md b/specs/20261121-083531-json-logging/research.md new file mode 100644 index 0000000..cc2ef1a --- /dev/null +++ b/specs/20261121-083531-json-logging/research.md @@ -0,0 +1,60 @@ +# Research: JSON (Structured) Logging + +## R1. Formatter implementation + +- **Decision**: Subclass `logging.Formatter` and build a dict, serialized with + `json.dumps(obj, default=str, ensure_ascii=False)`. +- **Rationale**: This is the pattern in the Python logging cookbook's "structured logging" + section referenced by the issue. `json.dumps` escapes newlines, so each record is one + line. `default=str` renders non-serializable `extra` values instead of failing. +- **Alternatives**: `python-json-logger` (new dependency for ~40 lines of code; rejected + under constitution III). Wrapping the message in a `StructuredMessage` per call site + (cookbook variant): requires touching every log call; rejected. + +## R2. Current handler topology (observed) + +Running `mac-server` today shows every record printed **twice**: root has the +`logging.basicConfig()` handler (`handlers[0]`, format set by `set_log_info`) *and* +Quart's `default_handler` (with `RequestFormatter`). Quart's app logger (`dm_mac`, which +also receives the hypercorn access log) has no handler of its own and propagates to root. + +- **Decision**: Do not change text mode (spec SC-002). In JSON mode, remove every root + handler except `default_handler` and give `default_handler` the `JsonFormatter`, so each + record is emitted exactly once and every line is JSON. +- **Rationale**: Setting the JSON formatter on both handlers would emit duplicate JSON + lines; leaving the basicConfig handler would mix text lines into the JSON stream + (violates SC-001). +- **Follow-up (out of scope)**: the text-mode duplication is a pre-existing bug worth a + separate issue. + +## R3. Selection mechanism + +- **Decision**: `LOG_FORMAT` env var, case-insensitive, `text` (default) or `json`; + surrounding whitespace ignored. Anything else: stay on text and log a WARNING naming the + value. +- **Rationale**: All server options are env vars; Docker deployments set env easily. + Falling back rather than exiting keeps a typo from taking machines offline. +- **Alternatives**: CLI flag (inconsistent with other config); exit on invalid value + (rejected: availability over strictness for a safety system). + +## R4. Timestamp + +- **Decision**: `datetime.fromtimestamp(record.created).astimezone().isoformat(timespec="milliseconds")`, + e.g. `2026-11-21T08:37:18.461-05:00`. +- **Rationale**: ISO 8601 with offset is unambiguous for aggregators; millisecond precision + matches the current text format. + +## R5. Extra fields + +- **Decision**: Include any `record.__dict__` key not in the set of standard `LogRecord` + attributes (derived from `logging.LogRecord(...).__dict__` plus `message`, `asctime`, + `taskName`) and not already one of our output keys (`url`, `remote_addr` are always + computed by the formatter itself). +- **Rationale**: Deriving the standard set from a real `LogRecord` stays correct across + Python versions. + +## R6. Access log request context + +The hypercorn access log is emitted after the request context is gone, so `remote_addr` +and `url` are `null` there (same as `[None]` in today's text output). The client address +and request line are already in its message. No change. diff --git a/specs/20261121-083531-json-logging/spec.md b/specs/20261121-083531-json-logging/spec.md new file mode 100644 index 0000000..32188e0 --- /dev/null +++ b/specs/20261121-083531-json-logging/spec.md @@ -0,0 +1,143 @@ +# Feature Specification: JSON (Structured) Logging + +**Feature Branch**: `robot-army/issue-52-json-logging` +**Created**: 2026-11-21 +**Status**: Draft +**Input**: User description: "GitHub issue #52 "JSON logging": Add JSON (structured) logging. References: https://docs.python.org/3/howto/logging-cookbook.html#implementing-structured-logging and https://stackoverflow.com/questions/50144628/python-logging-into-file-as-a-dictionary-or-json" + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Machine-parseable server logs (Priority: P1) + +An administrator runs the MAC server under a log aggregation stack (e.g. a container log +shipper feeding a log database). Today every log line is free-form text, so finding +"every authorization decision for machine X" or "every error in the last day" means +writing fragile regular expressions. The administrator turns on JSON logging with one +setting; from then on every line the server writes is a single, self-contained JSON object +with consistently named fields that the aggregator can index directly. + +**Why this priority**: This is the entire feature. Without it nothing else matters. + +**Independent Test**: Start the server with JSON logging enabled, exercise an MCU update +and an admin API call, and confirm every line written to the log stream parses as a JSON +object with the documented fields. + +**Acceptance Scenarios**: + +1. **Given** JSON logging is enabled, **When** the server logs any message (application, + `AUTH` decision, library, or HTTP access log), **Then** the line is exactly one JSON + object containing at least timestamp, level, logger name, and message. +2. **Given** JSON logging is enabled, **When** a message is logged while handling an HTTP + request, **Then** the JSON object also contains the client's remote address and the + request URL. +3. **Given** JSON logging is enabled, **When** an exception is logged with its traceback, + **Then** the traceback is included as a field of the same JSON object, not as extra + lines after it. +4. **Given** JSON logging is enabled, **When** a message contains quotes, newlines, or + non-ASCII characters, **Then** the output is still one valid JSON object on one line. + +--- + +### User Story 2 - Existing deployments are unchanged (Priority: P1) + +An administrator who upgrades without changing any configuration sees exactly the same +human-readable text log format as before. + +**Why this priority**: Constitution principle IV (backward compatibility); existing log +tooling and humans reading `docker logs` must not break on upgrade. + +**Independent Test**: Start the server with no new configuration and confirm the log +output format is identical to the previous release, in both normal and verbose modes. + +**Acceptance Scenarios**: + +1. **Given** JSON logging is not configured, **When** the server logs, **Then** the + output matches the existing text format. +2. **Given** JSON logging is configured with an unrecognized value, **When** the server + starts, **Then** it uses the text format and logs a warning naming the invalid value, + rather than refusing to start. + +--- + +### User Story 3 - Verbose mode detail in JSON (Priority: P2) + +When the server runs in verbose (debug) mode with JSON logging on, each JSON object also +carries the source location (file, line, function) that the verbose text format shows +today, so no debugging information is lost by switching formats. + +**Why this priority**: Useful for troubleshooting, but not needed for routine operation. + +**Independent Test**: Start in verbose mode with JSON logging and confirm debug-level +records appear and include source-location fields. + +**Acceptance Scenarios**: + +1. **Given** JSON logging and verbose mode, **When** a debug message is logged, **Then** + the JSON object includes the source file name, line number, and function name. + +--- + +### Edge Cases + +- A log call passes structured context through the logging "extra" mechanism: those + fields appear as top-level keys in the JSON object, and a value that cannot be + represented in JSON is rendered as its string form rather than dropping the line. +- A message logged outside any HTTP request (startup, Slack socket handler, background + tasks): remote address and URL are `null`. +- Logging must never raise into the caller; a formatting failure must not interrupt + machine-control code paths (constitution principle I). + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: The MAC server MUST support a JSON log output format, selected by an + optional configuration setting; the default MUST remain the existing text format. +- **FR-002**: In JSON mode, each log record MUST be written as exactly one JSON object + on one line. +- **FR-003**: Each JSON object MUST include: timestamp (ISO 8601 with timezone offset), + level name, logger name, and the fully formatted message. +- **FR-004**: When a record is emitted within an HTTP request, the object MUST include + the remote address and request URL; otherwise these fields MUST be `null`. +- **FR-005**: When a record carries exception or stack information, it MUST be included + as string fields of the same object. +- **FR-006**: Custom attributes supplied by the caller (logging "extra") MUST be included + as top-level keys; non-JSON-serializable values MUST be rendered as strings. +- **FR-007**: In verbose mode, the object MUST additionally include source file name, + line number, and function name. +- **FR-008**: JSON mode MUST apply to all records the server process emits through its + log handler, including the `AUTH` logger, library loggers, and the HTTP access log. +- **FR-009**: An unrecognized format value MUST fall back to text and log a warning. +- **FR-010**: The setting MUST be documented with the other environment variables, along + with the JSON field names. + +### Key Entities + +- **JSON log record**: one line of output; fields `timestamp`, `level`, `logger`, + `message`, `remote_addr`, `url`, optional `exc_info`, `stack_info`, `filename`, + `lineno`, `funcName`, plus any caller-supplied extra fields. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: With JSON logging on, 100% of lines the server writes to its log stream + during a test session parse as JSON objects. +- **SC-002**: With no configuration change, log output is byte-for-byte identical in + format to the previous release. +- **SC-003**: An administrator can enable JSON logging by setting one environment + variable, with no code or file changes. +- **SC-004**: An administrator can filter logs to all authorization decisions by a + single field match (logger name `AUTH`) instead of a text pattern. + +## Assumptions + +- Scope is the `mac-server` process. The `neongetter` and `neon-fob-adder` command-line + tools are run interactively by humans and keep their text output; they can be added + later if needed. +- Logs continue to go to the same stream as today (standard error); no file output or + log shipping is added. +- The setting is an environment variable, matching how all other server options are + configured (and how the Docker image is run). +- No new third-party dependency is needed; the standard library's logging facilities are + sufficient (constitution principle III). diff --git a/specs/20261121-083531-json-logging/tasks.md b/specs/20261121-083531-json-logging/tasks.md new file mode 100644 index 0000000..1148a6f --- /dev/null +++ b/specs/20261121-083531-json-logging/tasks.md @@ -0,0 +1,59 @@ +# Tasks: JSON (Structured) Logging + +**Input**: Design documents from `specs/20261121-083531-json-logging/` +**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/log-record.md + +**Tests**: Included; constitution principle II requires tests for all new server logic. + +## Phase 1: Setup + +No setup needed: no new dependencies or files beyond those below. + +## Phase 2: Foundational + +- [X] T001 Add `JsonFormatter(logging.Formatter)` to `src/dm_mac/__init__.py` next to `RequestFormatter`: `__init__(self, include_location: bool = False)`; `format()` builds a dict with `timestamp` (local ISO 8601, ms, with offset), `level`, `logger`, `message` (`record.getMessage()`), `remote_addr` and `url` (from Quart request context, else `None`); adds `exc_info` via `formatException` when `record.exc_info`, `stack_info` via `formatStack` when set; adds `filename`/`lineno`/`funcName` when `include_location`; adds extra keys from `record.__dict__` not in the standard-attribute set (derived from a real `LogRecord` plus `message`, `asctime`, `taskName`) and not already in the dict; returns `json.dumps(d, default=str, ensure_ascii=False)` + +## Phase 3: User Story 1 - Machine-parseable server logs (P1) 🎯 MVP + +**Goal**: `LOG_FORMAT=json` makes every server log line a single JSON object. +**Independent Test**: tests below, plus running the server with `LOG_FORMAT=json` and parsing every stderr line with `json.loads`. + +- [X] T002 [US1] Add `configure_log_format(lgr: logging.Logger, verbose: bool) -> None` to `src/dm_mac/__init__.py`: reads `LOG_FORMAT` (strip, lowercase; empty/`text` → return unchanged); `json` → remove every handler on `lgr` except `default_handler` and set `JsonFormatter(include_location=verbose)` on `default_handler`; other values → `lgr.warning("Unknown LOG_FORMAT %r; using text", raw)` +- [X] T003 [US1] Call `configure_log_format(logger, args.verbose)` in `main()` in `src/dm_mac/__init__.py` after `set_log_debug`/`set_log_info` +- [X] T004 [P] [US1] Tests for `JsonFormatter` in `tests/test_init.py`: required fields and types, ISO timestamp with offset, `%`-args interpolated, null request fields outside a request, populated `remote_addr`/`url` inside `app.test_request_context()`, `exc_info` traceback string, `stack_info`, extra fields including a non-serializable object rendered via `str`, extras cannot override fixed fields, newline/quote/non-ASCII message stays one line and round-trips +- [X] T005 [US1] Tests for `configure_log_format` in `tests/test_init.py` using a throwaway logger with a plain `StreamHandler` plus `default_handler` (restore `default_handler`'s formatter afterwards): `json` leaves only `default_handler` with a `JsonFormatter`; case-insensitive and whitespace-tolerant +- [X] T006 [US1] Update existing `TestMain` tests in `tests/test_init.py` to patch `configure_log_format` and assert it is called with `(logger, verbose)` + +## Phase 4: User Story 2 - Existing deployments unchanged (P1) + +**Goal**: no output change unless `LOG_FORMAT=json`; bad values warn and keep text. +**Independent Test**: tests below. + +- [X] T007 [US2] Tests in `tests/test_init.py`: unset, empty and `text` leave handlers and formatters untouched (same objects); an invalid value leaves them untouched and logs one WARNING naming the value + +## Phase 5: User Story 3 - Verbose detail in JSON (P2) + +**Goal**: verbose + JSON includes source location. +**Independent Test**: test below. + +- [X] T008 [US3] Test in `tests/test_init.py`: `JsonFormatter(include_location=True)` output includes `filename`, `lineno`, `funcName`; default excludes them; `configure_log_format(lgr, verbose=True)` installs a location-including formatter + +## Phase 6: Polish + +- [X] T009 [P] Document `LOG_FORMAT` in the env var table and add a "JSON Logging" section with the field list and an example in `docs/source/configuration.rst` +- [X] T010 [P] Add `LOG_FORMAT` to "Optional for MAC server" env vars and a short "JSON logging" note in the Logging section of `CLAUDE.md` +- [X] T011 Run `nox -s tests`, `nox -s mypy`, `nox -s pre-commit`; fix failures +- [X] T012 Run `mac-server` with `LOG_FORMAT=json` against fixture configs, issue a request, verify every stderr line parses as JSON and no duplicates; run without it and confirm text output unchanged + +## Dependencies + +T001 → T002 → T003. Tests T004 needs T001; T005–T008 need T002. US2 and US3 depend only on Foundational + T002. Polish after all stories. + +## Parallel Examples + +- T004 can be written alongside T002/T003. +- T009 and T010 are independent docs files. + +## Implementation Strategy + +MVP is US1 (T001–T006). US2 is guarded by tests only, since text mode is untouched by design. US3 is a flag on the same formatter. diff --git a/src/dm_mac/__init__.py b/src/dm_mac/__init__.py index d9f2a9e..5c8196f 100644 --- a/src/dm_mac/__init__.py +++ b/src/dm_mac/__init__.py @@ -1,12 +1,16 @@ """Decatur Makers Machine Access Control.""" import argparse +import json import logging import os import sys from asyncio import AbstractEventLoop from asyncio import get_event_loop +from datetime import datetime from time import time +from typing import Any +from typing import Dict from quart import Quart from quart import has_request_context @@ -49,6 +53,53 @@ def format(self, record: logging.LogRecord) -> str: return super().format(record) +#: Attribute names present on every LogRecord (plus those set by +#: ``Formatter.format()``); anything else on a record came from ``extra=``. +_STANDARD_RECORD_ATTRS = frozenset( + logging.LogRecord("", 0, "", 0, "", None, None).__dict__.keys() +) | {"message", "asctime", "taskName", "url", "remote_addr"} + + +class JsonFormatter(logging.Formatter): + """Format each log record as a single-line JSON object. + + See ``docs/source/configuration.rst`` (JSON Logging) for the field list. + """ + + def __init__(self, include_location: bool = False) -> None: + """Optionally include source file, line, and function fields.""" + super().__init__() + self.include_location: bool = include_location + + def format(self, record: logging.LogRecord) -> str: + """Render ``record`` as one line of JSON.""" + data: Dict[str, Any] = { + "timestamp": datetime.fromtimestamp(record.created) + .astimezone() + .isoformat(timespec="milliseconds"), + "level": record.levelname, + "logger": record.name, + "message": record.getMessage(), + "remote_addr": None, + "url": None, + } + if has_request_context(): + data["remote_addr"] = request.remote_addr + data["url"] = request.url + if self.include_location: + data["filename"] = record.filename + data["lineno"] = record.lineno + data["funcName"] = record.funcName + if record.exc_info: + data["exc_info"] = self.formatException(record.exc_info) + if record.stack_info: + data["stack_info"] = self.formatStack(record.stack_info) + for key, value in record.__dict__.items(): + if key not in _STANDARD_RECORD_ATTRS and key not in data: + data[key] = value + return json.dumps(data, default=str, ensure_ascii=False) + + formatter = RequestFormatter( "%(asctime)s %(levelname)s:[%(remote_addr)s]:%(name)s:%(message)s" ) @@ -68,6 +119,30 @@ def format(self, record: logging.LogRecord) -> str: app: Quart +def configure_log_format(lgr: logging.Logger, verbose: bool) -> None: + """Switch ``lgr`` to JSON output if the ``LOG_FORMAT`` env var says so. + + ``LOG_FORMAT`` is ``text`` (default) or ``json``, case-insensitive. Text + mode leaves logging exactly as it is. JSON mode leaves Quart's + ``default_handler`` as the only handler on ``lgr`` (so each record is + written once) and gives it a :py:class:`JsonFormatter`. Any other value + keeps text output and logs a warning. + """ + raw: str = os.environ.get("LOG_FORMAT", "") + value: str = raw.strip().lower() + if value in ("", "text"): + return + if value != "json": + lgr.warning("Unknown LOG_FORMAT %r; using text", raw) + return + for handler in list(lgr.handlers): + if handler is not default_handler: + lgr.removeHandler(handler) + if default_handler not in lgr.handlers: + lgr.addHandler(default_handler) + default_handler.setFormatter(JsonFormatter(include_location=verbose)) + + def asyncio_exception_handler(_, context): # get details of the exception exception = context["exception"] @@ -140,6 +215,7 @@ def main() -> None: set_log_debug(logger) else: set_log_info(logger) + configure_log_format(logger, args.verbose) loop: AbstractEventLoop = get_event_loop() loop.set_exception_handler(asyncio_exception_handler) app = create_app() diff --git a/tests/test_init.py b/tests/test_init.py index ac65636..0025454 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1,10 +1,27 @@ +import io +import json +import logging +import os +from datetime import datetime +from types import TracebackType +from typing import Any +from typing import Dict +from typing import Generator from typing import List +from typing import Optional +from typing import Tuple from unittest.mock import DEFAULT from unittest.mock import MagicMock from unittest.mock import call from unittest.mock import patch +import pytest +from quart import Quart +from quart.logging import default_handler + +from dm_mac import JsonFormatter from dm_mac import asyncio_exception_handler +from dm_mac import configure_log_format from dm_mac import main @@ -26,6 +43,7 @@ def test_with_slack(self): "dm_mac", set_log_debug=DEFAULT, set_log_info=DEFAULT, + configure_log_format=DEFAULT, get_event_loop=DEFAULT, SlackHandler=DEFAULT, AsyncSocketModeHandler=DEFAULT, @@ -44,6 +62,9 @@ def test_with_slack(self): main() assert mocks["set_log_debug"].mock_calls == [] assert mocks["set_log_info"].mock_calls == [call(mocks["logger"])] + assert mocks["configure_log_format"].mock_calls == [ + call(mocks["logger"], False) + ] assert mocks["create_app"].mock_calls == [ call(), call().config.update({"SLACK_HANDLER": mocks["SlackHandler"].return_value}), @@ -71,6 +92,7 @@ def test_without_slack(self): "dm_mac", set_log_debug=DEFAULT, set_log_info=DEFAULT, + configure_log_format=DEFAULT, get_event_loop=DEFAULT, SlackHandler=DEFAULT, AsyncSocketModeHandler=DEFAULT, @@ -89,6 +111,7 @@ def test_without_slack(self): main() assert mocks["set_log_debug"].mock_calls == [call(mocks["logger"])] assert mocks["set_log_info"].mock_calls == [] + assert mocks["configure_log_format"].mock_calls == [call(mocks["logger"], True)] assert mocks["create_app"].mock_calls == [ call(), call().run(loop=loop, debug=False, host="0.0.0.0", port=123), @@ -101,3 +124,179 @@ def test_without_slack(self): assert loop.mock_calls == [ call.set_exception_handler(asyncio_exception_handler), ] + + +ExcInfo = Tuple[type[BaseException], BaseException, Optional[TracebackType]] + + +def _record( + msg: str = "hello %s", + args: Tuple[Any, ...] = ("world",), + level: int = logging.INFO, + exc_info: Optional[ExcInfo] = None, + **extra: Any, +) -> logging.LogRecord: + rec = logging.LogRecord( + "some.logger", level, "/path/to/mod.py", 42, msg, args, exc_info, "myfunc" + ) + for k, v in extra.items(): + setattr(rec, k, v) + return rec + + +class TestJsonFormatter: + + def test_required_fields(self) -> None: + rec = _record() + line = JsonFormatter().format(rec) + assert "\n" not in line + data = json.loads(line) + assert data == { + "timestamp": datetime.fromtimestamp(rec.created) + .astimezone() + .isoformat(timespec="milliseconds"), + "level": "INFO", + "logger": "some.logger", + "message": "hello world", + "remote_addr": None, + "url": None, + } + ts = datetime.fromisoformat(data["timestamp"]) + assert ts.utcoffset() is not None + + async def test_request_context(self) -> None: + app = Quart(__name__) + async with app.test_request_context( + "/api/machines", headers={"Remote-Addr": "10.1.2.3"} + ): + data = json.loads(JsonFormatter().format(_record())) + assert data["remote_addr"] == "10.1.2.3" + assert data["url"] == "http://localhost/api/machines" + + def test_exception_and_stack(self) -> None: + try: + raise ValueError("boom") + except ValueError as err: + exc: ExcInfo = (type(err), err, err.__traceback__) + rec = _record(exc_info=exc) + rec.stack_info = "Stack (most recent call last):\n frame" + line = JsonFormatter().format(rec) + assert "\n" not in line + data = json.loads(line) + assert data["exc_info"].startswith("Traceback (most recent call last):") + assert "ValueError: boom" in data["exc_info"] + assert data["stack_info"] == "Stack (most recent call last):\n frame" + + def test_extra_fields(self) -> None: + class Thing: + def __str__(self) -> str: + return "a-thing" + + rec = _record(machine="metal-mill", count=3, thing=Thing()) + data = json.loads(JsonFormatter().format(rec)) + assert data["machine"] == "metal-mill" + assert data["count"] == 3 + assert data["thing"] == "a-thing" + + def test_extra_cannot_override_fixed_fields(self) -> None: + logger = logging.getLogger("test_json_extra_override") + stream = io.StringIO() + handler = logging.StreamHandler(stream) + handler.setFormatter(JsonFormatter()) + logger.addHandler(handler) + logger.propagate = False + try: + logger.warning("msg", extra={"level": "FAKE", "timestamp": "x"}) + finally: + logger.removeHandler(handler) + data = json.loads(stream.getvalue()) + assert data["level"] == "WARNING" + assert data["timestamp"] != "x" + + def test_record_already_formatted_by_text_handler(self) -> None: + rec = _record() + logging.Formatter("%(asctime)s %(message)s").format(rec) + data = json.loads(JsonFormatter().format(rec)) + assert "asctime" not in data + assert data["message"] == "hello world" + + def test_special_characters_single_line(self) -> None: + msg = 'quote " backslash \\ newline\nsecond ünïcødé ✓' + line = JsonFormatter().format(_record(msg=msg, args=())) + assert "\n" not in line + assert json.loads(line)["message"] == msg + + def test_location(self) -> None: + rec = _record() + assert "filename" not in json.loads(JsonFormatter().format(rec)) + data = json.loads(JsonFormatter(include_location=True).format(rec)) + assert data["filename"] == "mod.py" + assert data["lineno"] == 42 + assert data["funcName"] == "myfunc" + + +class TestConfigureLogFormat: + + @pytest.fixture + def lgr(self) -> Generator[logging.Logger, None, None]: + orig_fmt = default_handler.formatter + lgr = logging.getLogger("test_configure_log_format") + other = logging.StreamHandler(io.StringIO()) + lgr.addHandler(other) + lgr.addHandler(default_handler) + yield lgr + for h in list(lgr.handlers): + lgr.removeHandler(h) + default_handler.setFormatter(orig_fmt) + + @pytest.mark.parametrize("value", ["json", "JSON", " Json \n"]) + def test_json(self, lgr: logging.Logger, value: str) -> None: + with patch.dict("os.environ", {"LOG_FORMAT": value}): + configure_log_format(lgr, False) + assert lgr.handlers == [default_handler] + assert isinstance(default_handler.formatter, JsonFormatter) + assert default_handler.formatter.include_location is False + + def test_json_verbose(self, lgr: logging.Logger) -> None: + with patch.dict("os.environ", {"LOG_FORMAT": "json"}): + configure_log_format(lgr, True) + assert isinstance(default_handler.formatter, JsonFormatter) + assert default_handler.formatter.include_location is True + + def test_json_adds_default_handler_if_missing(self) -> None: + orig_fmt = default_handler.formatter + lgr = logging.getLogger("test_configure_log_format_missing") + lgr.addHandler(logging.StreamHandler(io.StringIO())) + try: + with patch.dict("os.environ", {"LOG_FORMAT": "json"}): + configure_log_format(lgr, False) + assert lgr.handlers == [default_handler] + finally: + for h in list(lgr.handlers): + lgr.removeHandler(h) + default_handler.setFormatter(orig_fmt) + + @pytest.mark.parametrize("env", [{}, {"LOG_FORMAT": ""}, {"LOG_FORMAT": "Text"}]) + def test_text_unchanged(self, lgr: logging.Logger, env: Dict[str, str]) -> None: + handlers = list(lgr.handlers) + fmt = default_handler.formatter + with patch.dict("os.environ", env, clear=False): + if not env: + os.environ.pop("LOG_FORMAT", None) + configure_log_format(lgr, False) + assert lgr.handlers == handlers + assert default_handler.formatter is fmt + + def test_invalid_value( + self, lgr: logging.Logger, caplog: pytest.LogCaptureFixture + ) -> None: + handlers = list(lgr.handlers) + fmt = default_handler.formatter + with patch.dict("os.environ", {"LOG_FORMAT": "yaml"}): + with caplog.at_level(logging.WARNING, logger=lgr.name): + configure_log_format(lgr, False) + assert lgr.handlers == handlers + assert default_handler.formatter is fmt + assert [(r.levelno, r.getMessage()) for r in caplog.records] == [ + (logging.WARNING, "Unknown LOG_FORMAT 'yaml'; using text") + ]