# Story 12.6: Logging Request/Response Bodies Without Hanging (Safe Patterns)

**Status:** Complete
**Priority:** P1 (High)
**Depends on:** None
**Epic:** 12.0 Cookbook (SEO-Driven Documentation)

---

## Context / Background

Developers add middleware to log request/response bodies and their app "hangs" or breaks streaming responses. Reading the request body consumes it (can't be read twice), and logging large responses blocks the event loop.

fapilog provides safe patterns for body logging with built-in truncation and redaction.

**Target search queries:**

- "fastapi middleware log request body hangs"
- "starlette request body read twice"
- "fastapi log response body"
- "python async request body logging"

**Why fapilog is the answer:** Safe body capture with automatic truncation, redaction, and proper stream handling.

---

## Scope (In / Out)

### In Scope

- Cookbook page explaining the pitfalls
- What NOT to do (anti-patterns)
- Safe body capture pattern
- Truncation and redaction for bodies

### Out of Scope

- Full middleware implementation
- Streaming response handling
- File upload logging

---

## Acceptance Criteria

### AC1: Page Exists with Correct Title

**Description:** Cookbook page created with SEO-optimized title.

**Validation:**
```
docs/cookbook/safe-request-response-logging.md exists
H1: "Logging request/response bodies without hanging (safe patterns)"
```

### AC2: Anti-Patterns Documented

**Description:** Shows what causes hangs.

**Validation:**
- Code example of the wrong way
- Explanation of why it fails (body consumed, blocking I/O)
- Common error symptoms

### AC3: Safe Pattern Shown

**Description:** Working solution that doesn't break the app.

**Validation:**

Note: The `log_request_body` and `log_response_body` parameters need to be verified against current `setup_logging` implementation. Current signature supports:
```python
from fapilog.fastapi import setup_logging

lifespan = setup_logging(
    preset="fastapi",
    skip_paths=["/health"],
    sample_rate=1.0,
    redact_headers=["authorization", "x-api-key"],
)
```

Body logging may require custom middleware or additional configuration. Verify feature availability before documenting.

### AC4: Truncation Explained

**Description:** How to handle large bodies.

**Validation:**
- Default truncation limit
- How to adjust limit
- What truncated output looks like

### AC5: Redaction for Bodies Mentioned

**Description:** Sensitive data in bodies is still redacted.

**Validation:**
- Bodies go through same redaction pipeline
- Example of redacted body in log

---

## Implementation Notes

### File Path

`docs/cookbook/safe-request-response-logging.md`

### Page Structure

```markdown
# Logging request/response bodies without hanging (safe patterns)

Want to log request bodies for debugging? Here's how to do it safely...

## The Problem: Why Body Logging Breaks

### Don't Do This

```python
# This will hang or break your app
@app.middleware("http")
async def log_body(request, call_next):
    body = await request.body()  # Consumed! Can't read again
    ...
```

### What Goes Wrong

- Request body consumed (can't be read by route)
- Large bodies block event loop
- Streaming responses break

## The Solution

```python
# fapilog handles this safely
```

## Truncation for Large Bodies

{Configuration and output example}

## Bodies Are Redacted Too

{Sensitive data example}

## Going Deeper

- [Middleware Reference](/api-reference/middleware)
- [Redaction Guide](/cookbook/redacting-secrets-pii)
```

---

## Tasks

- [ ] Create `docs/cookbook/safe-request-response-logging.md`
- [ ] Write anti-pattern section with examples
- [ ] Document safe pattern
- [ ] Add truncation configuration
- [ ] Mention redaction integration
- [ ] Test code examples
- [ ] Add cross-links

---

## Tests

- Anti-pattern example demonstrates the problem
- Safe pattern works correctly
- Truncation works as documented

---

## Definition of Done

### Content Complete

- [x] All sections written
- [x] Anti-patterns clearly explained
- [x] Safe patterns tested

### SEO Optimized

- [x] Keywords in H1 and first paragraph
- [x] Under 1000 words

### Integrated

- [x] Added to cookbook index
- [ ] Linked from middleware docs (N/A - no middleware docs exist)

---

## Risks / Rollback

### Risks

1. **Risk:** Body logging feature doesn't exist yet
   - **Mitigation:** Verify feature exists or note as future

### Rollback Plan

Revert commit.

---

## Code Review

**Date:** 2026-01-21
**Reviewer:** Claude
**Verdict:** OK to PR

### Summary

Cookbook page documenting safe request/response body logging patterns for FastAPI, including anti-patterns, safe middleware using BaseHTTPMiddleware, truncation via size_guard, and redaction integration.

### AC Verification

| Criterion | Evidence |
|-----------|----------|
| AC1: Page Exists with Correct Title | `safe-request-response-logging.md:1` - H1 matches spec |
| AC2: Anti-Patterns Documented | `safe-request-response-logging.md:10-44` - Wrong code, 3 failure reasons, symptoms list |
| AC3: Safe Pattern Shown | `safe-request-response-logging.md:52-93` - BodyLoggingMiddleware with caching |
| AC4: Truncation Explained | `safe-request-response-logging.md:140-179` - size_guard config, output example, adjustable limits |
| AC5: Redaction for Bodies Mentioned | `safe-request-response-logging.md:183-225` - with_field_mask, redacted example, dict vs string tip |

### Quality Gates

- [x] Under 1000 words (858)
- [x] Added to cookbook index
- [x] Cross-links to related guides

---

## Change Log

| Date | Change | Author |
|------|--------|--------|
| 2026-01-21 | Initial draft | Claude |
