Skip to content

Chapter 19 · Production Deployment and Monitoring ​

Chapter goals: Master deployment, logging, and monitoring configuration for HTTP clients in production environments.

19.1 Structured Logging ​

python
import logging
import requests

# Configure requests logging
logging.basicConfig(level=logging.DEBUG)
http_client_logger = logging.getLogger('httpx' or 'requests')
http_client_logger.setLevel(logging.INFO)

# Enable request logging
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

resp = requests.get('https://api.example.com/data')
logging.info(f'Request completed: status={resp.status_code}')

19.2 httpx Logging Configuration ​

python
import httpx
import logging

# Enable detailed httpx logging
logging.basicConfig(level=logging.DEBUG)
httpx_logger = logging.getLogger('httpx')
httpx_logger.setLevel(logging.INFO)

with httpx.Client() as client:
    resp = client.get('https://httpbin.org/get')

19.3 Performance Metrics Collection ​

python
import time
import requests

def timed_request(url: str, **kwargs) -> dict:
    start = time.perf_counter()
    resp = requests.get(url, **kwargs)
    elapsed = time.perf_counter() - start
    
    return {
        'url': url,
        'status': resp.status_code,
        'duration_ms': round(elapsed * 1000, 2),
        'size_bytes': len(resp.content)
    }

# Usage
result = timed_request('https://api.example.com/data')
print(f"Duration: {result['duration_ms']}ms")

19.4 Health Checks ​

python
import requests
from typing import Dict, List

def check_endpoints(endpoints: List[str]) -> Dict[str, bool]:
    """Check availability of multiple API endpoints"""
    results = {}
    for url in endpoints:
        try:
            resp = requests.head(url, timeout=5)
            results[url] = resp.status_code < 500
        except requests.exceptions.RequestException:
            results[url] = False
    return results

# Usage
health = check_endpoints([
    'https://api.example.com/health',
    'https://db.example.com/status'
])

19.5 Graceful Shutdown ​

python
import signal
import requests

session = requests.Session()

def graceful_shutdown(signum, frame):
    print('Closing connection pool...')
    session.close()
    exit(0)

signal.signal(signal.SIGTERM, graceful_shutdown)
signal.signal(signal.SIGINT, graceful_shutdown)

# Normal request processing
resp = session.get('https://api.example.com/data')

19.6 Chapter Summary ​

  • Configure structured logging for easier troubleshooting;
  • Record request duration and response size for performance monitoring;
  • Implement health check endpoints for service monitoring;
  • Register signal handlers to ensure the connection pool is properly closed.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. Which logger controls requests library request logging?

2. What is the purpose of graceful session shutdown?

3. What should a production health check do?

4. What metrics should performance monitoring record?

🛠️ Hands-on Practice ​

  1. Configure httpx request logging to output each request's URL and status code.
  2. Implement a request-timing decorator to log API call duration.
  3. Write a health check function that periodically monitors multiple endpoints and alerts on failures.

After completing the exercises, move to Next chapter: Capstone Project.