Skip to content

Commit 161c383

Browse files
committed
Refine structured logging skill documentation
1 parent 761337f commit 161c383

11 files changed

Lines changed: 372 additions & 554 deletions

File tree

‎.gitignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
11
/just/local.just
2+
.idea
3+
.venv
4+
venv
5+
.uv*
6+
.DS_Store

‎README.md‎

Lines changed: 44 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
# Python Structured Logging Skill
22

3-
Agent skill for adding, reviewing, refactoring, and standardizing structured logging in Python services. This repo follows the [Agent Skills specification](https://agentskills.io/specification), so it can be used by skills-compatible agents including Claude Code and Codex CLI.
3+
`python-structured-logging` is a skill for coding agents working in Python codebases that need clearer, safer, and more queryable logs. It helps with practical tasks such as reviewing noisy log statements, replacing `print` debugging, standardizing event names and fields, and improving exception logging.
44

5-
The bundled skill is:
5+
The canonical skill id is `python-structured-logging`. This repository is named `python-structured-logging-skill` and packages that skill for skills-compatible agent environments.
66

7-
- `python-structured-logging`: Improve Python logging with a `structlog`-first approach, while also supporting the standard library `logging` module. Covers event naming, structured fields, bound context, exception logging, correlation IDs, noise reduction, and sensitive-data redaction.
8-
9-
## Installation
7+
## Quickstart
108

119
### Marketplace
1210

@@ -15,29 +13,31 @@ The bundled skill is:
1513
/plugin install python-structured-logging@python-structured-logging-skill
1614
```
1715

16+
Use the marketplace path only if your agent runtime supports these plugin commands.
17+
1818
### npx skills
1919

2020
```text
2121
npx skills add git@github.com:mrKazzila/python-structured-logging-skill.git
2222
```
2323

24-
Instead of SSH, if you prefer HTTPS:
24+
If you prefer HTTPS:
2525

2626
```text
2727
npx skills add https://github.com/mrKazzila/python-structured-logging-skill
2828
```
2929

30-
### Manually
30+
### Manual install
3131

3232
#### Claude Code
3333

34-
Copy the contents of this repo into a `/.claude` folder in the root of the project where you want the skill to be available.
34+
Copy this repository into the target project's `/.claude` folder.
3535

3636
See the [official Claude Skills documentation](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview).
3737

3838
#### Codex CLI
3939

40-
Copy the contents of [`plugins/python-structured-logging/skills/`](plugins/python-structured-logging/skills/) into your Codex skills path, typically `~/.codex/skills`.
40+
Copy [`plugins/python-structured-logging/skills/python-structured-logging`](plugins/python-structured-logging/skills/python-structured-logging) into your Codex skills path, typically `~/.codex/skills/python-structured-logging`.
4141

4242
See the [Agent Skills specification](https://agentskills.io/specification) for the standard skill format.
4343

@@ -51,18 +51,45 @@ git clone https://github.com/mrKazzila/python-structured-logging-skill.git ~/.op
5151

5252
Do not copy only the inner `skills/` folder. OpenCode auto-discovers `SKILL.md` files under `~/.opencode/skills/`.
5353

54-
## Skills
54+
The skill inspects the logging stack already in use before changing anything. If the project already uses `structlog`, it leans into bound context and structured fields. If the project intentionally uses stdlib `logging`, it improves event names, `extra` payloads, and traceback handling without forcing a migration.
55+
56+
## What's Inside
57+
58+
- Main skill: [`plugins/python-structured-logging/skills/python-structured-logging/SKILL.md`](plugins/python-structured-logging/skills/python-structured-logging/SKILL.md)
59+
- Examples: [`examples/structlog`](plugins/python-structured-logging/skills/python-structured-logging/examples/structlog) and [`examples/stdlib`](plugins/python-structured-logging/skills/python-structured-logging/examples/stdlib)
60+
- Reference guide: [`references/Python Logging Style Guide.md`](plugins/python-structured-logging/skills/python-structured-logging/references/Python Logging Style Guide.md)
61+
- Agent metadata: [`agents/openai.yaml`](plugins/python-structured-logging/skills/python-structured-logging/agents/openai.yaml)
62+
63+
## When to Use This Skill
5564

56-
| Skill | Description |
57-
|-------|-------------|
58-
| [python-structured-logging](plugins/python-structured-logging/skills/python-structured-logging) | Add, review, refactor, and standardize structured logging in Python codebases, primarily with `structlog` and secondarily with the standard library `logging` module |
65+
- Adding or upgrading logging in a Python service, worker, CLI, or background job.
66+
- Reviewing whether existing logs are structured, stable, and operationally useful.
67+
- Replacing `print` statements and ad hoc debug logging.
68+
- Introducing structured fields into existing `structlog` or stdlib `logging` code.
69+
- Standardizing event names and field names across modules or teams.
70+
- Debugging production behavior that needs better context and lower noise.
5971

60-
## Validation
72+
## When Not to Use
6173

62-
To validate the skill folder structure and frontmatter, run:
74+
- The user explicitly asked not to change logging behavior.
75+
- The task is a one-off throwaway script where logging would add more noise than value.
76+
- The project has strict logging conventions and the current task is unrelated to logging or observability.
77+
78+
## Verify / Contribute
79+
80+
- Edit the skill or reference guide.
81+
- Update examples if the recommended behavior changes.
82+
- Run checks before finishing:
6383

6484
```sh
65-
uv run --with pyyaml python "${CODEX_HOME:-$HOME/.codex}/skills/.system/skill-creator/scripts/quick_validate.py" plugins/python-structured-logging/skills/python-structured-logging
85+
just validate
86+
python scripts/check_release_state.py
6687
```
6788

68-
This uses the validator bundled with the local `skill-creator` skill installation.
89+
- `just validate` uses `uv` plus `pyyaml`. If `pyyaml` is not already available, `uv` may need a writable cache and network access to fetch it.
90+
- `uv run python scripts/check_release_state.py` is an equivalent release-state check if you prefer to keep the command under `uv`.
91+
- Keep the skill concise, direct, and usable by agents during review and refactoring.
92+
93+
## License
94+
95+
This project is licensed under the terms in [LICENSE](LICENSE).
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"name": "python-structured-logging",
3-
"description": "Adds a skill for adding, reviewing, and refactoring structured logging in Python services.",
3+
"description": "Adds the python-structured-logging skill for reviewing and improving Python application logs.",
44
"version": "0.1.0"
5-
}
5+
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"name": "python-structured-logging",
3-
"description": "Adds a skill for adding, reviewing, and refactoring structured logging in Python services.",
3+
"description": "Adds the python-structured-logging skill for reviewing and improving Python application logs.",
44
"version": "0.1.0"
5-
}
5+
}
Lines changed: 127 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,147 @@
11
---
22
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.
44
---
55

66
# Python Structured Logging
77

8-
Improve logs so they are useful to operators, safe to ship, and easy to query.
8+
## Core Rule
99

10-
## Use this workflow
10+
Logs are operational events, not developer diary entries.
1111

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
2113

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.
2322

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
3124

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.
3329

34-
Check each touched log statement for:
30+
Good:
3531

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+
```
4436

45-
## Framework guidance
37+
Bad:
4638

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+
```
5044

51-
## Use bundled resources
45+
## Fields and Context
5246

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.
5652

57-
## Output expectations
53+
Good:
5854

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+
```
6059

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.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
interface:
22
display_name: "Python Structured Logging"
3-
short_description: "Improve structured logging in Python services"
4-
default_prompt: "Use $python-structured-logging to review and improve structured logging in this Python codebase."
3+
short_description: "Practical guidance for safer, more useful Python logs"
4+
default_prompt: "Use $python-structured-logging to inspect the current Python logging stack, tighten event names and fields, and improve exception logging without forcing an unnecessary migration."

‎plugins/python-structured-logging/skills/python-structured-logging/examples/stdlib/bad.py‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,27 @@
44
logger = logging.getLogger(__name__)
55

66

7-
def process_invoice(invoice_id: str, customer_id: str, attempt: int, duration_ms: int) -> None:
7+
def process_invoice(
8+
invoice_id: str,
9+
customer_id: str,
10+
request_id: str,
11+
attempt: int,
12+
payment_payload: dict,
13+
) -> None:
14+
print("starting invoice processing", invoice_id, customer_id, request_id)
815
logger.info(
9-
f"Starting invoice processing for invoice={invoice_id}, customer={customer_id}, attempt={attempt}"
16+
f"processing invoice {invoice_id} for customer {customer_id} attempt={attempt}"
1017
)
1118

1219
try:
1320
logger.info(
14-
f"Invoice {invoice_id} for customer {customer_id} processed in {duration_ms} ms"
21+
f"invoice_{invoice_id}_processed",
22+
extra={
23+
"payload": payment_payload,
24+
"request": request_id,
25+
"authorization_header": "Bearer secret-token",
26+
},
1527
)
1628
except Exception as exc:
17-
logger.error(f"Invoice processing failed for {invoice_id}: {exc}")
18-
raise
29+
logger.error(f"invoice processing failed for {invoice_id}: {exc}")
30+
return

0 commit comments

Comments
 (0)