Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .specify/feature.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"feature_directory": "specs/002-second-relay-support"
"feature_directory": "specs/20261121-083531-json-logging"
}
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -276,4 +279,5 @@ We have a special process for developing features. When asked to begin work on a
<!-- SPECKIT START -->
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
<!-- SPECKIT END -->
40 changes: 40 additions & 0 deletions docs/source/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
37 changes: 37 additions & 0 deletions specs/20261121-083531-json-logging/checklists/requirements.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 21 additions & 0 deletions specs/20261121-083531-json-logging/contracts/log-record.md
Original file line number Diff line number Diff line change
@@ -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 '<value>'; 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 ..."}
```
19 changes: 19 additions & 0 deletions specs/20261121-083531-json-logging/data-model.md
Original file line number Diff line number Diff line change
@@ -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.
61 changes: 61 additions & 0 deletions specs/20261121-083531-json-logging/plan.md
Original file line number Diff line number Diff line change
@@ -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.
17 changes: 17 additions & 0 deletions specs/20261121-083531-json-logging/quickstart.md
Original file line number Diff line number Diff line change
@@ -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")'`.
60 changes: 60 additions & 0 deletions specs/20261121-083531-json-logging/research.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading