# Story 12.9: Graceful Shutdown & Flushing Logs (Don't Lose Logs on Deploy)

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

---

## Context / Background

Containerized applications are frequently restarted during deployments. If the log buffer isn't flushed before shutdown, recent logs are lost. This is especially painful when debugging deployment-related issues.

fapilog integrates with FastAPI's lifespan to ensure logs are flushed on graceful shutdown.

**Target search queries:**

- "flush logs on shutdown python"
- "fastapi graceful shutdown logging"
- "kubernetes python logging lost"
- "don't lose logs on deploy"

**Why fapilog is the answer:** Automatic flush on shutdown when using lifespan integration.

---

## Scope (In / Out)

### In Scope

- Cookbook page explaining the lost logs problem
- Lifespan integration for automatic flush
- Manual flush API for custom scenarios
- Timeout handling during shutdown

### Out of Scope

- Kubernetes deployment strategies
- SIGTERM handling deep dive
- Log persistence/durability guarantees

---

## Acceptance Criteria

### AC1: Page Exists with Correct Title

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

**Validation:**
```
docs/cookbook/graceful-shutdown-flush.md exists
H1: "Graceful shutdown & flushing logs (don't lose logs on deploy)"
```

### AC2: Problem Explained

**Description:** Why logs get lost on shutdown.

**Validation:**
- Async buffer explanation
- SIGTERM timing issues
- Real-world deployment scenario

### AC3: Automatic Flush Shown

**Description:** How fapilog handles this automatically.

**Validation:**
```python
from fapilog.fastapi import setup_logging

lifespan = setup_logging()  # Flush handled automatically
app = FastAPI(lifespan=lifespan)
```

### AC4: Manual Flush Documented

**Description:** For custom shutdown scenarios.

**Validation:**
```python
from fapilog import get_async_logger

logger = await get_async_logger()

# In custom shutdown handler - use drain() for complete shutdown
async def shutdown():
    await logger.drain()  # Flushes and stops workers
```

Note: The logger has `drain()` method for graceful shutdown, not `flush()`. The `drain()` method ensures all queued logs are written before returning.

### AC5: Timeout Handling Mentioned

**Description:** What happens if flush takes too long.

**Validation:**
- Default timeout
- How to configure
- What happens when timeout exceeded

---

## Implementation Notes

### File Path

`docs/cookbook/graceful-shutdown-flush.md`

### Page Structure

```markdown
# Graceful shutdown & flushing logs (don't lose logs on deploy)

Your last log before a crash might be the most important one...

## The Problem: Lost Logs on Shutdown

{Buffered logs lost when container killed}
{Debugging deployment issues without logs}

## The Solution: Lifespan Integration

```python
# Automatic flush on shutdown
lifespan = setup_logging()
```

## Manual Flush API

{For custom scenarios}

## Timeout Handling

{What if flush is slow}

## Going Deeper

- [Lifespan Reference](/api-reference/lifespan)
- [FastAPI Integration](/guides/fastapi)
```

---

## Tasks

- [ ] Create `docs/cookbook/graceful-shutdown-flush.md`
- [ ] Write lost logs problem section
- [ ] Document automatic flush
- [ ] Add manual flush API
- [ ] Document timeout behavior
- [ ] Test code examples
- [ ] Add cross-links

---

## Tests

- Logs flushed on shutdown
- Manual flush works
- Timeout behavior correct

---

## Definition of Done

### Content Complete

- [x] All sections written
- [x] Code examples tested
- [x] Timeout behavior verified

### SEO Optimized

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

### Integrated

- [x] Added to cookbook index
- [ ] Linked from deployment guide (N/A - no user-facing deployment guide exists)

---

## Risks / Rollback

### Risks

1. **Risk:** Flush behavior not implemented
   - **Mitigation:** Verify against codebase

### Rollback Plan

Revert commit.

---

## Code Review

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

### Summary

Reviewed cookbook page for graceful shutdown and log flushing. All acceptance criteria met with correct API usage.

### AC Verification

| Criterion | Evidence |
|-----------|----------|
| AC1: Page Exists | `graceful-shutdown-flush.md:1` - H1 matches spec |
| AC2: Problem Explained | `graceful-shutdown-flush.md:5-31` - Buffer, SIGTERM, scenarios |
| AC3: Automatic Flush | `graceful-shutdown-flush.md:35-40` - setup_logging() |
| AC4: Manual Flush | `graceful-shutdown-flush.md:53-66` - drain() with stats |
| AC5: Timeout | `graceful-shutdown-flush.md:81-127` - Config and behavior |

### Quality Gates

- [x] Sphinx build passed (-W flag)
- [x] Word count under 1000 (685)
- [x] Cross-links valid

---

## Change Log

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