codingstairs
노트에듀라이프연락
⌕검색⌘K
koen

Navigation

  • Intro
  • Blog
  • Life

연락하기

로그인 없이도 보낼 수 있어요. 답변이 필요하면 이메일을 함께 적어 주세요.

  • 익명 폼으로 의견 남기기 →
  • ✉ warragon112@gmail.com
  • 카카오톡 오픈채팅 ↗

© 2026 codingstairs

  • 노트
  • 에듀
  • 검색
  • 라이프
  • 연락
  • 약관
  • RSS
  • GitHub
에듀›Python · FastAPI · 데이터 파이프라인›7단계

7단계

7단계 — 헬스체크·관측

0회 조회

7단계 — 헬스체크·관측

서버는 살아 있어야 가치가 있어요. 그리고 살아 있는지 누가 어떻게 알지 결정하는 게 관측(observability).

헬스체크 엔드포인트

# routers/health.py
from fastapi import APIRouter, status
from db.connection import get_conn

router = APIRouter()

@router.get("/health")
def health():
    return {"status": "ok"}

@router.get("/health/db")
def health_db():
    try:
        with get_conn() as conn, conn.cursor() as cur:
            cur.execute("SELECT 1")
            cur.fetchone()
        return {"db": "ok"}
    except Exception as e:
        return {"db": "down", "error": str(e)}, status.HTTP_503_SERVICE_UNAVAILABLE

/health 는 앱이 응답하는지, /health/db 는 DB 까지 연결되는지. 모니터링 시스템이 5분마다 호출.

Docker HEALTHCHECK

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD curl -f http://localhost:8000/health || exit 1

이 한 줄로 docker-compose 가 건강한 컨테이너만 의존성에 포함시켜요.

구조화 로깅

import logging
import json

class JsonFormatter(logging.Formatter):
    def format(self, record):
        return json.dumps({
            "ts": self.formatTime(record),
            "level": record.levelname,
            "msg": record.getMessage(),
            "module": record.module,
        }, ensure_ascii=False)

handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logging.getLogger().addHandler(handler)

JSON 으로 로그를 남기면 Loki·CloudWatch·Datadog 같은 도구가 자동 파싱·검색.

메트릭 — Prometheus

from prometheus_client import Counter, Histogram, generate_latest

requests_total = Counter("http_requests_total", "총 HTTP 요청 수", ["method", "path"])
request_duration = Histogram("http_request_duration_seconds", "HTTP 요청 시간")

@router.get("/metrics")
def metrics():
    return Response(generate_latest(), media_type="text/plain")

Grafana 가 /metrics 를 1분마다 긁어가 그래프로.

알림 — 무엇이 깨지면 누구에게

세 가지만 정해 두면 절반은 됩니다.

  • 무엇 — DB 연결 실패 / 5xx 에러율 > 1% / 메모리 > 80%
  • 누구 — Slack 채널 또는 이메일
  • 언제 깨움 — 평일 09~18 만 / 24/7

직접 해 보기

/health + /health/db 두 엔드포인트를 추가하고 Dockerfile 에 HEALTHCHECK 를 넣어 보세요. docker compose ps 했을 때 STATUS 가 healthy 면 성공.

더 깊이

  • 관측 · 로깅 · 에러 노트

다음 단계

마지막 8단계에서는 지금까지의 라우터·비동기·검증·의존성·에러 처리를 모아 실무에서 깨지지 않는 FastAPI 패턴 으로 다듬어요.

← 6단계

6단계 — 데이터 파이프라인

8단계 →

8단계 — FastAPI 실무 패턴