콘텐츠 대표 이미지 - Python 모니터링과 성능 지표 수집을위한 도구 활용 완전 정복 🚀
🐍 Python · 프로그램개발

Python 모니터링과 성능 지표 수집을
위한 도구 활용 완전 정복 🚀

내 코드가 숨 쉬는 방식을 들여다보자 — 실전 중심 가이드

야, 솔직히 말해봐. 코드 짜고 나서 "어, 잘 돌아가네~" 하고 끝낸 적 있지? 😅
근데 실제 서비스에 올라가면 갑자기 느려지거나, 메모리가 폭발하거나, CPU가 100%를 찍는 상황이 생기잖아.
그때 가서 "왜 이러지?" 하면서 당황하는 거, 진짜 개발자라면 한 번쯤은 겪어봤을 거야.

그래서 오늘은 Python 모니터링과 성능 지표 수집에 대해 제대로 파헤쳐볼 거야.
어떤 도구들이 있는지, 어떻게 쓰는지, 실전에서 어떻게 활용하는지까지 — 친구한테 설명하듯 쭉 풀어볼게. 🎯

Python 모니터링 생태계 한눈에 보기 Python 앱 서버 psutil 시스템 리소스 Prometheus 지표 수집·저장 cProfile 코드 프로파일링 Grafana 시각화 대시보드 logging 로그 수집 OpenTelemetry 분산 추적

🔍

왜 모니터링이 필요한가? — 진짜 이유

"내 로컬에서는 잘 됐는데요" — 이 말, 개발자 세계에서 전설의 밈이 된 이유가 있어. 😂
로컬 환경과 프로덕션 환경은 완전히 달라. 트래픽, 데이터 크기, 동시 접속자 수, 서버 스펙까지 전부 다르거든.

🎯 모니터링이 필요한 핵심 이유 3가지 1. 성능 병목 발견 — 어떤 함수가 느린지, 어디서 시간을 잡아먹는지 정확히 알 수 있어.
2. 메모리 누수 탐지 — 서버가 시간이 지날수록 느려진다면? 메모리 누수일 가능성이 높아.
3. 장애 예방 — 임계값을 설정해두면 문제가 터지기 전에 알림을 받을 수 있어.

실제로 넷플릭스, 구글, 아마존 같은 빅테크 기업들은 수백 개의 마이크로서비스를 운영하면서
초당 수백만 건의 지표를 수집하고 있어. 그게 가능한 이유가 바로 잘 설계된 모니터링 시스템 덕분이야.

💡 Tip: 모니터링은 "문제가 생겼을 때" 보는 게 아니라, "문제가 생기기 전에" 미리 파악하는 도구야.
사후 대응이 아닌 사전 예방이 핵심이라는 거 기억해!

💻

psutil — 시스템 리소스의 모든 것을 꿰뚫어보기

psutil은 Python에서 시스템 리소스를 모니터링할 때 가장 먼저 배우는 라이브러리야.
CPU, 메모리, 디스크, 네트워크, 프로세스 정보까지 — 운영체제가 알고 있는 거의 모든 걸 Python으로 가져올 수 있어.

📦 설치

terminal
pip install psutil

🔧 기본 사용법 — CPU & 메모리 모니터링

python
import psutil
import time

# CPU 사용률 (1초 간격으로 측정)
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU 사용률: {cpu_percent}%")

# CPU 코어별 사용률
per_cpu = psutil.cpu_percent(interval=1, percpu=True)
for i, usage in enumerate(per_cpu):
    print(f"  코어 {i}: {usage}%")

# 메모리 정보
mem = psutil.virtual_memory()
print(f"전체 메모리: {mem.total / (1024**3):.2f} GB")
print(f"사용 중: {mem.used / (1024**3):.2f} GB")
print(f"사용률: {mem.percent}%")
print(f"여유 메모리: {mem.available / (1024**3):.2f} GB")

🔧 디스크 & 네트워크 모니터링

python
import psutil

# 디스크 사용량
disk = psutil.disk_usage('/')
print(f"디스크 전체: {disk.total / (1024**3):.1f} GB")
print(f"디스크 사용: {disk.used / (1024**3):.1f} GB")
print(f"디스크 여유: {disk.free / (1024**3):.1f} GB")
print(f"사용률: {disk.percent}%")

# 네트워크 I/O
net_io = psutil.net_io_counters()
print(f"수신 바이트: {net_io.bytes_recv / (1024**2):.2f} MB")
print(f"송신 바이트: {net_io.bytes_sent / (1024**2):.2f} MB")

🔧 프로세스 모니터링 — 특정 프로세스 추적

python
import psutil
import os

# 현재 실행 중인 Python 프로세스 정보
current_process = psutil.Process(os.getpid())

print(f"프로세스 ID: {current_process.pid}")
print(f"CPU 사용률: {current_process.cpu_percent(interval=1)}%")
print(f"메모리 사용: {current_process.memory_info().rss / (1024**2):.2f} MB")
print(f"스레드 수: {current_process.num_threads()}")
print(f"열린 파일 수: {len(current_process.open_files())}")
✅ psutil 핵심 포인트 Windows, macOS, Linux 모두 지원하는 크로스플랫폼 라이브러리야.
특히 cpu_percent(interval=1)에서 interval 파라미터를 꼭 설정해야 정확한 값이 나와.
interval=None이면 마지막 호출 이후의 사용률을 반환하는데, 처음 호출 시엔 0.0이 나올 수 있거든.

⏱️

cProfile & line_profiler — 코드 어디가 느린지 X-레이 찍기

시스템 리소스 모니터링도 중요하지만, 진짜 핵심은 "내 코드의 어느 부분이 느린가"야.
이걸 알아내는 게 바로 프로파일링(Profiling)이야.

🔬 cProfile — Python 내장 프로파일러

cProfile은 Python 표준 라이브러리에 포함된 프로파일러야. 별도 설치 없이 바로 쓸 수 있어.

python
import cProfile
import pstats
import io

def slow_function():
    total = 0
    for i in range(1000000):
        total += i ** 2
    return total

def fast_function():
    return sum(i ** 2 for i in range(1000000))

# 프로파일링 실행
profiler = cProfile.Profile()
profiler.enable()

slow_function()
fast_function()

profiler.disable()

# 결과 출력
stream = io.StringIO()
stats = pstats.Stats(profiler, stream=stream)
stats.sort_stats('cumulative')  # 누적 시간 기준 정렬
stats.print_stats(10)           # 상위 10개 함수만 출력
print(stream.getvalue())

커맨드라인에서도 바로 실행할 수 있어:

terminal
# 스크립트 전체 프로파일링
python -m cProfile -s cumulative my_script.py

# 결과를 파일로 저장
python -m cProfile -o output.prof my_script.py

# 저장된 결과 분석
python -m pstats output.prof

🔬 line_profiler — 라인별 실행 시간 측정

cProfile이 함수 단위라면, line_profiler는 코드 한 줄 한 줄의 실행 시간을 보여줘.
"이 함수가 느리다"는 건 알겠는데, "함수 안에서 어느 줄이 느린지"를 알고 싶을 때 쓰는 거야.

terminal
pip install line_profiler
python
from line_profiler import LineProfiler

def process_data(data):
    result = []
    for item in data:
        # 이 부분이 느릴 수 있어
        processed = item ** 2 + item * 3 + 1
        result.append(processed)
    return result

# 프로파일러 설정
lp = LineProfiler()
lp_wrapper = lp(process_data)

# 실행
data = list(range(100000))
lp_wrapper(data)

# 결과 출력
lp.print_stats()
💡 실전 팁: @profile 데코레이터를 함수 위에 붙이고
kernprof -l -v my_script.py로 실행하면 더 편하게 라인별 프로파일링을 할 수 있어!

📊 cProfile 출력 결과 해석하기

컬럼명 의미
ncalls 함수 호출 횟수
tottime 해당 함수 자체 실행 시간 (하위 함수 제외)
percall 호출 1회당 평균 시간 (tottime / ncalls)
cumtime 누적 실행 시간 (하위 함수 포함)
filename:lineno 파일명과 줄 번호

🧠

memory_profiler — 메모리 누수를 잡아라!

서버가 시간이 지날수록 점점 느려지고, 결국 OOM(Out of Memory) 에러로 죽어버리는 경험 해봤어?
그게 바로 메모리 누수(Memory Leak)야. 이걸 잡는 데 memory_profiler가 최고야.

terminal
pip install memory_profiler
python
from memory_profiler import profile, memory_usage
import time

@profile  # 이 데코레이터가 핵심!
def memory_hungry_function():
    # 큰 리스트 생성
    big_list = [i for i in range(1000000)]
    
    # 딕셔너리로 변환
    big_dict = {i: i**2 for i in range(100000)}
    
    # 처리
    result = sum(big_list)
    
    return result

memory_hungry_function()

실행하면 각 줄에서 메모리가 얼마나 증가했는지 MiB(메비바이트) 단위로 보여줘.
어느 줄에서 메모리가 급격히 늘어나는지 바로 파악할 수 있어.

🔧 시간에 따른 메모리 사용량 추적

python
from memory_profiler import memory_usage
import matplotlib.pyplot as plt

def my_function():
    data = []
    for i in range(100):
        data.extend([i] * 10000)
        import time
        time.sleep(0.01)
    return data

# 0.1초 간격으로 메모리 사용량 측정
mem_usage = memory_usage(my_function, interval=0.1)
print(f"최대 메모리 사용: {max(mem_usage):.2f} MiB")
print(f"최소 메모리 사용: {min(mem_usage):.2f} MiB")
⚠️ 메모리 누수 주요 원인들 1. 전역 변수에 계속 데이터 추가 — 함수 밖의 리스트/딕셔너리에 계속 append하는 패턴
2. 순환 참조 — 객체 A가 B를 참조하고, B가 다시 A를 참조하는 경우
3. 캐시 미관리 — LRU 캐시 크기 제한 없이 무한정 쌓이는 경우
4. 이벤트 리스너 미해제 — 등록한 콜백을 제거하지 않는 경우

Prometheus + Grafana 모니터링 파이프라인 Python 앱 지표 생성 (prometheus_client) HTTP /metrics Prometheus 지표 수집·저장 (시계열 DB) PromQL 쿼리 Grafana 시각화 (대시보드) 알림 발송 AlertManager 알림 관리 (Slack, Email) 📊 수집 가능한 지표 유형 • Counter: 단조 증가 카운터 (요청 수, 에러 수) • Gauge: 현재 값 (메모리 사용량, 활성 연결 수) • Histogram: 분포 측정 (응답 시간 분포) ⚡ 스크래핑 방식 • Pull 방식: Prometheus가 앱에서 직접 가져옴 • 기본 스크래핑 간격: 15초 • /metrics 엔드포인트 노출 필요 Python 앱이 지표를 생성하면 → Prometheus가 수집 → Grafana로 시각화 → 이상 감지 시 알림 발송 이 파이프라인 하나면 프로덕션 모니터링의 80%는 커버 가능해!

📡

prometheus_client — 프로덕션급 지표 수집의 표준

개인 프로젝트를 넘어서 실제 서비스를 운영한다면, Prometheus는 거의 필수야.
CNCF(Cloud Native Computing Foundation)의 공식 프로젝트이고, 쿠버네티스 생태계의 표준 모니터링 솔루션이거든.

terminal
pip install prometheus_client

🔧 기본 지표 타입 사용법

python
from prometheus_client import Counter, Gauge, Histogram, Summary
from prometheus_client import start_http_server
import time
import random

# 1. Counter: 단조 증가 (절대 감소하지 않는 값)
request_count = Counter(
    'http_requests_total',
    'HTTP 요청 총 횟수',
    ['method', 'endpoint', 'status']
)

# 2. Gauge: 현재 상태값 (증가/감소 모두 가능)
active_connections = Gauge(
    'active_connections',
    '현재 활성 연결 수'
)

# 3. Histogram: 값의 분포 측정
request_duration = Histogram(
    'http_request_duration_seconds',
    'HTTP 요청 처리 시간',
    buckets=[0.01, 0.05, 0.1, 0.5, 1.0, 2.0, 5.0]
)

# 4. Summary: 분위수(percentile) 측정
response_size = Summary(
    'http_response_size_bytes',
    'HTTP 응답 크기'
)

def handle_request(method, endpoint):
    # 요청 시작 시간 기록
    start_time = time.time()
    
    # 활성 연결 수 증가
    active_connections.inc()
    
    try:
        # 실제 처리 로직 (시뮬레이션)
        time.sleep(random.uniform(0.01, 0.5))
        status = "200"
        
        # 요청 카운터 증가
        request_count.labels(
            method=method,
            endpoint=endpoint,
            status=status
        ).inc()
        
    finally:
        # 처리 시간 기록
        duration = time.time() - start_time
        request_duration.observe(duration)
        
        # 활성 연결 수 감소
        active_connections.dec()

# HTTP 서버 시작 (포트 8000에서 /metrics 노출)
start_http_server(8000)
print("메트릭 서버 시작: http://localhost:8000/metrics")

# 시뮬레이션 실행
for i in range(100):
    handle_request("GET", "/api/users")
    time.sleep(0.1)

🔧 Flask 앱에 Prometheus 통합하기

python
from flask import Flask, request, Response
from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST
import time

app = Flask(__name__)

# 지표 정의
REQUEST_COUNT = Counter(
    'flask_request_count',
    'Flask 앱 요청 수',
    ['method', 'endpoint', 'http_status']
)

REQUEST_LATENCY = Histogram(
    'flask_request_latency_seconds',
    'Flask 요청 처리 시간',
    ['endpoint']
)

@app.before_request
def before_request():
    request.start_time = time.time()

@app.after_request
def after_request(response):
    # 요청 처리 시간 계산
    latency = time.time() - request.start_time
    
    # 지표 업데이트
    REQUEST_COUNT.labels(
        method=request.method,
        endpoint=request.path,
        http_status=response.status_code
    ).inc()
    
    REQUEST_LATENCY.labels(
        endpoint=request.path
    ).observe(latency)
    
    return response

@app.route('/metrics')
def metrics():
    return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)

@app.route('/api/hello')
def hello():
    return {"message": "안녕하세요!"}

if __name__ == '__main__':
    app.run(port=5000)
🎯 Prometheus 지표 네이밍 컨벤션 좋은 지표 이름은 라이브러리_서브시스템_단위 형식을 따라.
예: http_requests_total, process_cpu_seconds_total

단위는 항상 기본 단위를 써야 해 — 밀리초(ms) 대신 초(seconds), KB 대신 bytes.
그래야 나중에 Grafana에서 단위 변환이 편해.

📝

Python logging — 제대로 된 로그 시스템 구축하기

print()로 디버깅하는 시대는 끝났어. 😄
실제 서비스에서는 logging 모듈을 써야 해. 로그 레벨 관리, 파일 저장, 포맷 지정까지 다 되거든.

🔧 구조화된 로깅 설정

python
import logging
import json
from datetime import datetime

class JSONFormatter(logging.Formatter):
    """JSON 형식으로 로그를 출력하는 포매터"""
    
    def format(self, record):
        log_data = {
            "timestamp": datetime.utcnow().isoformat(),
            "level": record.levelname,
            "logger": record.name,
            "message": record.getMessage(),
            "module": record.module,
            "function": record.funcName,
            "line": record.lineno
        }
        
        # 예외 정보가 있으면 추가
        if record.exc_info:
            log_data["exception"] = self.formatException(record.exc_info)
        
        return json.dumps(log_data, ensure_ascii=False)

def setup_logger(name: str, level=logging.INFO) -> logging.Logger:
    logger = logging.getLogger(name)
    logger.setLevel(level)
    
    # 콘솔 핸들러
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(JSONFormatter())
    
    # 파일 핸들러 (일별 로테이션)
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(
        filename=f'logs/{name}.log',
        when='midnight',
        interval=1,
        backupCount=30,  # 30일치 보관
        encoding='utf-8'
    )
    file_handler.setFormatter(JSONFormatter())
    
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    
    return logger

# 사용 예시
logger = setup_logger('my_app')

logger.info("서버 시작됨", extra={"port": 8080})
logger.warning("메모리 사용률 높음", extra={"usage_percent": 85})
logger.error("데이터베이스 연결 실패", extra={"host": "db.example.com"})

📊 로그 레벨 정리

레벨 숫자값 사용 상황
DEBUG 10 개발 중 상세 디버깅 정보
INFO 20 정상적인 동작 확인 (서버 시작, 요청 처리 등)
WARNING 30 잠재적 문제 (메모리 높음, 응답 느림 등)
ERROR 40 오류 발생 (예외 처리, 연결 실패 등)
CRITICAL 50 심각한 오류 (서비스 중단 수준)
💡 실전 팁: 프로덕션에서는 INFO 레벨로 운영하고,
문제 발생 시에만 DEBUG로 낮춰서 상세 로그를 확인해.
DEBUG를 항상 켜두면 로그 파일이 엄청나게 커져서 디스크를 잡아먹어!

⚡

timeit & 컨텍스트 매니저 — 간단하고 정확한 성능 측정

무거운 프로파일러 없이 빠르게 성능을 측정하고 싶을 때 쓰는 방법들이야.
특히 두 가지 구현 방법 중 어느 게 더 빠른지 비교할 때 진짜 유용해.

🔧 timeit 모듈 활용

python
import timeit

# 방법 1: 리스트 컴프리헨션
list_comp_time = timeit.timeit(
    stmt='[i**2 for i in range(1000)]',
    number=10000  # 10000번 반복 실행
)

# 방법 2: map 함수
map_time = timeit.timeit(
    stmt='list(map(lambda x: x**2, range(1000)))',
    number=10000
)

print(f"리스트 컴프리헨션: {list_comp_time:.4f}초")
print(f"map 함수: {map_time:.4f}초")
print(f"차이: {abs(list_comp_time - map_time):.4f}초")

🔧 컨텍스트 매니저로 실행 시간 측정

python
import time
from contextlib import contextmanager

@contextmanager
def timer(name: str = ""):
    """실행 시간을 측정하는 컨텍스트 매니저"""
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        label = f"[{name}] " if name else ""
        print(f"{label}실행 시간: {elapsed:.6f}초 ({elapsed*1000:.3f}ms)")

# 사용 예시
with timer("데이터 처리"):
    data = [i**2 for i in range(1000000)]
    result = sum(data)

with timer("정렬"):
    sorted_data = sorted(data, reverse=True)

🔧 데코레이터로 함수 실행 시간 자동 측정

python
import time
import functools
import logging

logger = logging.getLogger(__name__)

def measure_time(func):
    """함수 실행 시간을 자동으로 측정하는 데코레이터"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        
        logger.info(
            f"함수 실행 완료",
            extra={
                "function": func.__name__,
                "duration_ms": round(elapsed * 1000, 3)
            }
        )
        return result
    return wrapper

@measure_time
def fetch_user_data(user_id: int):
    # DB 조회 시뮬레이션
    time.sleep(0.05)
    return {"id": user_id, "name": "홍길동"}

@measure_time
def process_order(order_id: int):
    # 주문 처리 시뮬레이션
    time.sleep(0.1)
    return {"order_id": order_id, "status": "완료"}

# 실행
user = fetch_user_data(123)
order = process_order(456)
🔑 time.perf_counter() vs time.time() time.time()은 시스템 시계를 반환해. 시스템 시간이 변경되면 영향을 받아.
time.perf_counter()는 고해상도 성능 카운터야. 시스템 시간과 무관하게 정확한 경과 시간을 측정해.
성능 측정에는 항상 perf_counter()를 써!

🌐

OpenTelemetry — 분산 시스템의 추적 표준

마이크로서비스 아키텍처에서는 하나의 요청이 여러 서비스를 거쳐가잖아.
"이 요청이 어디서 느려졌지?"를 알려면 분산 추적(Distributed Tracing)이 필요해.
그 표준이 바로 OpenTelemetry야.

terminal
pip install opentelemetry-api opentelemetry-sdk
pip install opentelemetry-exporter-otlp
python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor

# TracerProvider 설정
provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Tracer 생성
tracer = trace.get_tracer("my_service")

def get_user(user_id: int):
    # 스팬(Span) 생성 — 추적 단위
    with tracer.start_as_current_span("get_user") as span:
        span.set_attribute("user.id", user_id)
        
        # DB 조회 시뮬레이션
        import time
        time.sleep(0.05)
        
        user = {"id": user_id, "name": "홍길동"}
        span.set_attribute("user.name", user["name"])
        return user

def process_payment(user_id: int, amount: float):
    with tracer.start_as_current_span("process_payment") as span:
        span.set_attribute("payment.user_id", user_id)
        span.set_attribute("payment.amount", amount)
        
        # 사용자 조회 (중첩 스팬)
        user = get_user(user_id)
        
        # 결제 처리 시뮬레이션
        import time
        time.sleep(0.1)
        
        span.set_attribute("payment.status", "success")
        return {"status": "success", "user": user}

# 실행
with tracer.start_as_current_span("main_request"):
    result = process_payment(123, 50000.0)
    print(result)
✅ OpenTelemetry의 3가지 핵심 신호 Traces (추적) — 요청이 시스템을 통과하는 전체 경로를 기록해. 어디서 얼마나 걸렸는지 파악 가능.
Metrics (지표) — 시간에 따른 수치 데이터. CPU, 메모리, 요청 수 등.
Logs (로그) — 이벤트 기록. 위의 두 가지와 연결해서 맥락 파악 가능.

재능넷 같은 플랫폼에서 다양한 Python 개발자들이 활동하는데,
OpenTelemetry를 제대로 이해하고 있는 개발자는 마이크로서비스 프로젝트에서 정말 귀한 존재야. 💎


🏗️

실전 통합 예제 — 모든 걸 하나로 묶기

지금까지 배운 것들을 실제 서비스에서 어떻게 통합해서 쓰는지 보여줄게.
FastAPI 기반의 간단한 API 서버에 모니터링을 붙이는 예제야.

terminal
pip install fastapi uvicorn prometheus_client psutil
python
from fastapi import FastAPI, Request
from prometheus_client import Counter, Histogram, Gauge, generate_latest
from prometheus_client import CONTENT_TYPE_LATEST
import psutil
import time
import logging
import asyncio

# 로거 설정
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("api_server")

app = FastAPI(title="모니터링 통합 예제")

# Prometheus 지표 정의
REQUEST_COUNT = Counter(
    'api_requests_total',
    'API 요청 총 수',
    ['method', 'endpoint', 'status_code']
)

REQUEST_DURATION = Histogram(
    'api_request_duration_seconds',
    'API 요청 처리 시간',
    ['endpoint'],
    buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0]
)

ACTIVE_REQUESTS = Gauge(
    'api_active_requests',
    '현재 처리 중인 요청 수'
)

CPU_USAGE = Gauge('system_cpu_usage_percent', 'CPU 사용률')
MEMORY_USAGE = Gauge('system_memory_usage_percent', '메모리 사용률')

# 미들웨어: 모든 요청에 자동으로 지표 수집
@app.middleware("http")
async def monitor_requests(request: Request, call_next):
    start_time = time.perf_counter()
    ACTIVE_REQUESTS.inc()
    
    try:
        response = await call_next(request)
        status_code = response.status_code
    except Exception as e:
        logger.error(f"요청 처리 중 오류: {e}", exc_info=True)
        status_code = 500
        raise
    finally:
        duration = time.perf_counter() - start_time
        ACTIVE_REQUESTS.dec()
        
        REQUEST_COUNT.labels(
            method=request.method,
            endpoint=request.url.path,
            status_code=status_code
        ).inc()
        
        REQUEST_DURATION.labels(
            endpoint=request.url.path
        ).observe(duration)
        
        logger.info(
            f"{request.method} {request.url.path} "
            f"- {status_code} - {duration*1000:.2f}ms"
        )
    
    return response

# 시스템 지표 주기적 업데이트
async def update_system_metrics():
    while True:
        CPU_USAGE.set(psutil.cpu_percent(interval=1))
        MEMORY_USAGE.set(psutil.virtual_memory().percent)
        await asyncio.sleep(5)

@app.on_event("startup")
async def startup_event():
    logger.info("서버 시작됨")
    asyncio.create_task(update_system_metrics())

@app.get("/metrics")
async def metrics():
    from fastapi.responses import Response
    return Response(
        content=generate_latest(),
        media_type=CONTENT_TYPE_LATEST
    )

@app.get("/api/health")
async def health_check():
    cpu = psutil.cpu_percent()
    memory = psutil.virtual_memory()
    
    status = "healthy"
    if cpu > 80 or memory.percent > 85:
        status = "degraded"
    
    return {
        "status": status,
        "cpu_percent": cpu,
        "memory_percent": memory.percent,
        "memory_available_gb": round(memory.available / (1024**3), 2)
    }

@app.get("/api/users/{user_id}")
async def get_user(user_id: int):
    # 실제 DB 조회 시뮬레이션
    await asyncio.sleep(0.05)
    return {"id": user_id, "name": f"사용자_{user_id}"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
💡 이 코드의 핵심 포인트: 미들웨어 하나로 모든 엔드포인트의 요청 수, 처리 시간, 상태 코드를 자동으로 수집해.
백그라운드 태스크로 시스템 지표(CPU, 메모리)를 5초마다 업데이트하고,
/metrics 엔드포인트로 Prometheus가 수집해가는 구조야.

🗺️

상황별 도구 선택 가이드

도구가 너무 많아서 뭘 써야 할지 모르겠다고? 걱정 마, 상황별로 정리해줄게. 😊

상황 추천 도구 이유
코드 어느 부분이 느린지 찾기 cProfile + line_profiler 함수/라인 단위 정밀 분석
메모리 누수 찾기 memory_profiler 라인별 메모리 증감 추적
시스템 리소스 모니터링 psutil CPU/메모리/디스크/네트워크 통합
프로덕션 지표 수집 prometheus_client 업계 표준, Grafana 연동 용이
로그 관리 logging + JSON 포매터 구조화된 로그, ELK 스택 연동
마이크로서비스 추적 OpenTelemetry 분산 추적 표준, 벤더 중립적
빠른 성능 비교 timeit 간단하고 정확한 벤치마킹
🚀 모니터링 도입 단계별 로드맵 1단계 (입문) — logging 모듈 + psutil로 기본 로그와 시스템 지표 수집
2단계 (중급) — cProfile/line_profiler로 성능 병목 분석 + memory_profiler로 메모리 최적화
3단계 (고급) — prometheus_client + Grafana로 실시간 대시보드 구축
4단계 (전문) — OpenTelemetry로 분산 추적 + 알림 시스템 구축

🎓

마무리 — 모니터링은 개발의 완성이야

오늘 다룬 내용을 정리해보면:

1
psutil — 시스템 리소스(CPU, 메모리, 디스크, 네트워크)를 Python으로 쉽게 모니터링
2
cProfile & line_profiler — 코드의 성능 병목을 함수/라인 단위로 정밀 분석
3
memory_profiler — 메모리 누수를 라인별로 추적하고 최적화
4
prometheus_client — 프로덕션급 지표 수집의 업계 표준
5
logging 모듈 — 구조화된 로그로 문제 추적과 감사 로그 관리
6
OpenTelemetry — 마이크로서비스 환경에서의 분산 추적 표준
7
timeit & 컨텍스트 매니저 — 빠르고 정확한 성능 측정 유틸리티

모니터링은 "나중에 해야지"가 아니야. 처음부터 설계에 포함시켜야 하는 것이야.
코드를 짜면서 동시에 "이 부분은 어떻게 모니터링할까?"를 생각하는 습관이 진짜 시니어 개발자의 마인드셋이거든. 🧠

재능넷에서 Python 개발 관련 재능을 거래하거나 배울 때도,
모니터링과 성능 최적화 능력은 다른 개발자들과 차별화되는 핵심 역량이 될 거야.
오늘 배운 도구들을 하나씩 실제 프로젝트에 적용해보면서 익혀봐! 💪

댓글 작성

이 글에 대한 여러분의 생각을 들려주세요

댓글 0
댓글을 불러오는 중입니다.

아직 댓글이 없습니다.