|
1 | 1 | --- |
2 | 2 | name: python-structured-logging |
3 | | -description: Add, review, refactor, and standardize structured logging in Python codebases, primarily with structlog and secondarily with the standard library logging module. Use when Codex needs to improve logs in FastAPI apps, async workers, CLI tools, background jobs, Kafka or Redis consumers, Celery or taskiq tasks, or service-layer code, including event naming, canonical fields, bound context, exception logging, correlation IDs, noise reduction, and sensitive-data redaction. |
| 3 | +description: Use when reviewing or changing Python logging behavior, including structlog, stdlib logging, event naming, structured fields, bound context, exception logging, correlation IDs, or sensitive-data-safe observability. |
4 | 4 | --- |
5 | 5 |
|
6 | 6 | # Python Structured Logging |
7 | 7 |
|
8 | | -Improve logs so they are useful to operators, safe to ship, and easy to query. |
| 8 | +## Core Rule |
9 | 9 |
|
10 | | -## Use this workflow |
| 10 | +Logs are operational events, not developer diary entries. |
11 | 11 |
|
12 | | -1. Identify the logging stack already in use: `structlog`, stdlib `logging`, `loguru`, or a project wrapper. |
13 | | -2. Preserve existing conventions unless they are clearly harmful or the user asks to standardize them. |
14 | | -3. If `structlog` is available or already used, prefer it as the primary implementation style. |
15 | | -4. Prefer stable event names plus structured fields over interpolated text messages. |
16 | | -5. Bind shared request or task context once instead of repeating it in every call. |
17 | | -6. Keep one meaningful log per event boundary; remove noisy start or end chatter. |
18 | | -7. Preserve traceback data for unexpected failures and avoid duplicate exception logs across layers. |
19 | | -8. Remove or redact secrets, tokens, cookies, full payloads, and unnecessary personal data. |
20 | | -9. Verify changes with targeted tests or focused code inspection where possible. |
| 12 | +## Workflow |
21 | 13 |
|
22 | | -## Enforce these defaults |
| 14 | +1. Inspect the current stack first: `structlog`, stdlib `logging`, or a project wrapper. |
| 15 | +2. Preserve the current direction unless it is harmful or migration was explicitly requested. |
| 16 | +3. If the project uses stdlib `logging` intentionally, improve message shape and `extra` fields instead of forcing `structlog`. |
| 17 | +4. Replace prose or dynamic event names with stable `snake_case` events. |
| 18 | +5. Move variable data into structured fields and bind shared context once near the request or job boundary. |
| 19 | +6. Keep one meaningful exception log at the layer that owns the failure, with a traceback when needed. |
| 20 | +7. Remove or redact sensitive data before it reaches bound context or payload fields. |
| 21 | +8. Verify output shape, levels, and noise after the change. |
23 | 22 |
|
24 | | -- Write event names in `snake_case`. |
25 | | -- Keep event names short, stable, and free of variable values. |
26 | | -- Put variable data into fields such as `user_id`, `request_id`, `duration_ms`, `status`, or `reason`. |
27 | | -- Choose levels by operational meaning: `DEBUG` for diagnostics, `INFO` for expected events, `WARNING` for degradations or retries, `ERROR` for failed operations, `CRITICAL` only for service-threatening states. |
28 | | -- Use unit-bearing names such as `duration_ms`, `delay_seconds`, `size_bytes`, and `timeout_seconds`. |
29 | | -- Log success only when it is operationally meaningful. |
30 | | -- Add context at the layer where an operator can act on it; do not log and re-raise at every layer. |
| 23 | +## Event Naming |
31 | 24 |
|
32 | | -## Review checklist |
| 25 | +- Use stable `snake_case` event names. |
| 26 | +- Prefer action or action-plus-result names such as `invoice_processed` or `broker_publish_failed`. |
| 27 | +- Do not put IDs, emails, statuses, or exception text into the event name. |
| 28 | +- Do not use generic events such as `error`, `failed`, or `something_went_wrong` without the operation name. |
33 | 29 |
|
34 | | -Check each touched log statement for: |
| 30 | +Good: |
35 | 31 |
|
36 | | -- stable event naming; |
37 | | -- structured fields instead of f-strings or `%s`-style narrative text; |
38 | | -- useful identifiers and outcome fields; |
39 | | -- correct log level; |
40 | | -- traceback preservation on unexpected exceptions; |
41 | | -- absence of duplicated logs for the same failure path; |
42 | | -- absence of sensitive data leakage; |
43 | | -- signal-to-noise quality. |
| 32 | +```python |
| 33 | +logger.info("invoice_processed", invoice_id=invoice_id, duration_ms=duration_ms) |
| 34 | +logger.warning("retry_scheduled", attempt=attempt, delay_seconds=delay_seconds) |
| 35 | +``` |
44 | 36 |
|
45 | | -## Framework guidance |
| 37 | +Bad: |
46 | 38 |
|
47 | | -- For `structlog`, prefer `bind()` or `structlog.contextvars` for request or task scope. Keep events stable and pass variable data as keyword fields. |
48 | | -- For stdlib `logging`, prefer `extra=` or the project adapter rather than interpolating variables into the message. |
49 | | -- For wrappers or mixed stacks, fit the existing emission API and improve the event shape without forcing a full logging rewrite unless requested. |
| 39 | +```python |
| 40 | +logger.info(f"invoice {invoice_id} processed in {duration_ms} ms") |
| 41 | +logger.error(f"publish failed for order {order_id}") |
| 42 | +logger.info(f"user_{user_id}_updated") |
| 43 | +``` |
50 | 44 |
|
51 | | -## Use bundled resources |
| 45 | +## Fields and Context |
52 | 46 |
|
53 | | -- Read [references/Python Logging Style Guide.md](references/Python%20Logging%20Style%20Guide.md) when you need the full doctrine, naming guidance, field conventions, or rationale. |
54 | | -- Read [examples/structlog/good.py](examples/structlog/good.py) and [examples/structlog/bad.py](examples/structlog/bad.py) for the preferred structlog style. |
55 | | -- Read [examples/stdlib/good.py](examples/stdlib/good.py) and [examples/stdlib/bad.py](examples/stdlib/bad.py) when the project is intentionally using standard library logging without structlog. |
| 47 | +- Use stable field names such as `request_id`, `correlation_id`, `job_id`, `user_id`, `entity_id`, `status`, and `duration_ms` when they are relevant. |
| 48 | +- Bind shared context once when possible instead of passing the same fields manually everywhere. |
| 49 | +- Keep units in the key name: `duration_ms`, `delay_seconds`, `size_bytes`. |
| 50 | +- Avoid renaming the same concept across modules. |
| 51 | +- Prefer allowlisted payload fragments such as `{"amount_cents": ..., "card_last4": ...}` over raw payload logging. |
56 | 52 |
|
57 | | -## Output expectations |
| 53 | +Good: |
58 | 54 |
|
59 | | -When changing code: |
| 55 | +```python |
| 56 | +log = logger.bind(request_id=request_id, job_id=job_id) |
| 57 | +log.info("job_started", task_name=task_name) |
| 58 | +``` |
60 | 59 |
|
61 | | -- keep edits local to the touched flow; |
62 | | -- prefer a small number of canonical events over verbose traces; |
63 | | -- note any field naming standard you introduce; |
64 | | -- mention residual risks such as missing request context plumbing, absent JSON rendering, or unresolved sensitive-data exposure. |
| 60 | +Bad: |
| 61 | + |
| 62 | +```python |
| 63 | +logger.info("job started", extra={"req": request_id, "job": job_id}) |
| 64 | +logger.info("job_started", request_id=request_id, job_id=job_id) |
| 65 | +logger.info("job_finished", request_id=request_id, job_id=job_id) |
| 66 | +``` |
| 67 | + |
| 68 | +## Exception Logging |
| 69 | + |
| 70 | +- Use `logger.exception(...)` inside `except` when you need the traceback. |
| 71 | +- Use `exc_info=True` only when the logger API requires it. |
| 72 | +- Do not log and swallow unless that behavior is intentional and the caller does not need the failure. |
| 73 | +- Do not duplicate the same exception log at every layer. |
| 74 | +- Do not use `logger.error(str(exc))` as the only exception log for unexpected failures. |
| 75 | + |
| 76 | +Good: |
| 77 | + |
| 78 | +```python |
| 79 | +try: |
| 80 | + send_invoice(invoice) |
| 81 | +except ProviderTimeoutError: |
| 82 | + logger.exception("invoice_send_failed", invoice_id=invoice.id, retryable=True) |
| 83 | + raise |
| 84 | +``` |
| 85 | + |
| 86 | +Bad: |
| 87 | + |
| 88 | +```python |
| 89 | +try: |
| 90 | + send_invoice(invoice) |
| 91 | +except Exception as exc: |
| 92 | + logger.error(f"invoice failed: {exc}") |
| 93 | +``` |
| 94 | + |
| 95 | +## Sensitive Data |
| 96 | + |
| 97 | +- Never log passwords, tokens, API keys, cookies, authorization headers, private keys, or raw secrets. |
| 98 | +- Never log raw request bodies, raw response bodies, session data, personal data, or payment data unless the user explicitly asks for a safe, scoped format. |
| 99 | +- Prefer allowlisted fields over blocklists when logging payload-derived data. |
| 100 | +- Redact at boundaries before binding context. |
| 101 | + |
| 102 | +Good: |
| 103 | + |
| 104 | +```python |
| 105 | +safe_payment = { |
| 106 | + "card_last4": payment.card_last4, |
| 107 | + "amount_cents": payment.amount_cents, |
| 108 | +} |
| 109 | +logger.info("payment_authorized", payment=safe_payment) |
| 110 | +``` |
| 111 | + |
| 112 | +Bad: |
| 113 | + |
| 114 | +```python |
| 115 | +logger.info("payment_authorized", payload=payment_payload, auth_header=auth_header) |
| 116 | +``` |
| 117 | + |
| 118 | +## Noise Control |
| 119 | + |
| 120 | +- `INFO` for business or operational events that matter. |
| 121 | +- `DEBUG` for local diagnostics that can be turned off safely. |
| 122 | +- `WARNING` for degraded but handled situations such as retries or fallbacks. |
| 123 | +- `ERROR` for failed operations that need attention. |
| 124 | +- Avoid logs inside tight loops unless they are sampled or aggregated. |
| 125 | +- Remove `started` and `finished` chatter unless the boundary is operationally meaningful. |
| 126 | +- Prefer one outcome log over multiple step-by-step logs when the extra detail does not change operator action. |
| 127 | + |
| 128 | +## Bundled Resources |
| 129 | + |
| 130 | +- [`examples/structlog/good.py`](examples/structlog/good.py) |
| 131 | +- [`examples/structlog/bad.py`](examples/structlog/bad.py) |
| 132 | +- [`examples/stdlib/good.py`](examples/stdlib/good.py) |
| 133 | +- [`examples/stdlib/bad.py`](examples/stdlib/bad.py) |
| 134 | +- [`references/Python Logging Style Guide.md`](references/Python Logging Style Guide.md) |
| 135 | + |
| 136 | +- Read the examples that match the stack already in use. |
| 137 | +- Read the reference guide when you need human-oriented rationale, level guidance, or migration examples. |
| 138 | + |
| 139 | +## Verification Checklist |
| 140 | + |
| 141 | +- Current logging style is preserved or intentionally migrated. |
| 142 | +- Event names are stable and `snake_case`. |
| 143 | +- Variable data is in fields, not prose strings. |
| 144 | +- Shared context is bound or injected once where the stack supports it. |
| 145 | +- Exceptions include stack traces where needed. |
| 146 | +- Sensitive data is redacted or omitted. |
| 147 | +- Output still fits the project's log pipeline. |
0 commit comments