Yes, adding observability to your machine learning project is a great idea, as it allows you to monitor the performance, health, and behavior of your application in real-time. This can help in diagnosing issues, understanding user interactions, and ensuring reliability.
Below, I'll guide you through adding observability features to your FastAPI application using open-source tools that can run in Docker. We'll focus on logging, metrics, and tracing using tools like Prometheus, Grafana, Jaeger, and OpenTelemetry.
Overview
We'll integrate the following components:
- Logging: Capture and store logs for your application.
- Metrics: Use Prometheus to collect metrics from your application.
- Visualization: Use Grafana to visualize metrics and logs.
- Tracing: Use Jaeger for distributed tracing.
- Docker: Containerize your application and observability tools.
Step-by-Step Implementation
1. Enhance Your FastAPI Application
First, modify your FastAPI application to expose metrics and traces.
Install Required Dependencies
Add the following to your requirements.txt:
fastapi
uvicorn[standard]
prometheus_client
opentelemetry-api
opentelemetry-sdk
opentelemetry-exporter-jaeger
opentelemetry-instrumentation-fastapi
opentelemetry-instrumentation-logging
opentelemetry-instrumentation-requests
Install dependencies:
pip install -r requirements.txt
Modify main.py
Here's an example main.py with observability features:
from fastapi import FastAPI, Request
from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST
from starlette.responses import Response
import logging
import time
# OpenTelemetry imports
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.logging import LoggingInstrumentor
from opentelemetry.exporter.jaeger.thrift import JaegerExporter
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
# Prometheus metrics
REQUEST_COUNT = Counter('request_count', 'Total Request Count', ['method', 'endpoint'])
REQUEST_LATENCY = Histogram('request_latency_seconds', 'Request latency', ['endpoint'])
# Middleware to collect Prometheus metrics
@app.middleware("http")
async def prometheus_middleware(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
REQUEST_LATENCY.labels(endpoint=request.url.path).observe(process_time)
REQUEST_COUNT.labels(method=request.method, endpoint=request.url.path).inc()
return response
# Endpoint to expose metrics
@app.get("/metrics")
def metrics():
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
# Example endpoint
@app.get("/predict")
def predict():
# Your prediction logic here
return {"prediction": "survived"}
# Set up OpenTelemetry tracer
resource = Resource(attributes={
SERVICE_NAME: "titanic-ml-service"
})
trace.set_tracer_provider(TracerProvider(resource=resource))
tracer = trace.get_tracer(__name__)
# Configure Jaeger exporter
jaeger_exporter = JaegerExporter(
agent_host_name='jaeger', # Service name in Docker Compose
agent_port=6831,
)
span_processor = BatchSpanProcessor(jaeger_exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
# Instrument FastAPI and logging
FastAPIInstrumentor.instrument_app(app)
LoggingInstrumentor().instrument(set_logging_format=True)
2. Set Up Docker Environment
Create a Dockerfile to containerize your FastAPI application.
Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY ./app /app
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
docker-compose.yml
Create a docker-compose.yml file to run multiple services:
version: '3.8'
services:
app:
build: .
image: titanic-ml-service
container_name: titanic-ml-service
ports:
- "8000:8000"
depends_on:
- prometheus
- jaeger
prometheus:
image: prom/prometheus:v2.40.0
container_name: prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
command:
- '--config.file=/etc/prometheus/prometheus.yml'
ports:
- "9090:9090"
grafana:
image: grafana/grafana-oss
container_name: grafana
ports:
- "3000:3000"
jaeger:
image: jaegertracing/all-in-one:1.41
container_name: jaeger
environment:
- COLLECTOR_ZIPKIN_HOST_PORT=:9411
ports:
- "6831:6831/udp"
- "16686:16686"
- "14268:14268"
- "9411:9411"
prometheus.yml
Configure Prometheus to scrape metrics from your FastAPI application:
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'fastapi'
scrape_interval: 5s
static_configs:
- targets: ['app:8000']
labels:
group: 'fastapi-app'
3. Run the Environment
Build and run your Docker Compose environment:
docker-compose up --build
4. Access Services
- FastAPI Application:
http://localhost:8000
- Metrics Endpoint:
http://localhost:8000/metrics
- Prometheus:
http://localhost:9090
- Grafana:
http://localhost:3000 (Default credentials: admin/admin)
- Jaeger UI:
http://localhost:16686
Visualizing Metrics with Grafana
1. Configure Data Source
- Access Grafana at
http://localhost:3000.
- Log in with default credentials and change the password when prompted.
- Add Prometheus as a data source:
- Go to Configuration (Gear Icon) > Data Sources.
- Click Add data source.
- Select Prometheus.
- Set the URL to
http://prometheus:9090.
- Click Save & Test.
2. Import Dashboard
- You can import existing dashboards or create a new one.
- For a simple metrics dashboard:
- Go to Create + > Dashboard > Add Query.
- Use Prometheus metrics like
request_count and request_latency_seconds.
Viewing Traces with Jaeger
- Access Jaeger UI at
http://localhost:16686.
- Select your service (
titanic-ml-service) from the Service dropdown.
- Click Find Traces to view collected traces.
Adding Logging
While logging is set up in the FastAPI application using Python's logging module and instrumented with OpenTelemetry, you might want to centralize your logs.
Option 1: View Logs in Docker
Option 2: Centralized Logging with Grafana Loki (Optional)
To centralize logs, you can use Grafana Loki, a log aggregation system.
- Note: Adding Loki increases complexity. Here's how you can integrate it:
Update docker-compose.yml:
loki:
image: grafana/loki:2.7.1
container_name: loki
ports:
- "3100:3100"
command: -config.file=/etc/loki/local-config.yaml
volumes:
- ./loki-config.yaml:/etc/loki/local-config.yaml
promtail:
image: grafana/promtail:2.7.1
container_name: promtail
volumes:
- /var/lib/docker/containers:/var/lib/docker/containers:ro
- /var/log:/var/log:ro
- ./promtail-config.yaml:/etc/promtail/config.yml
command: -config.file=/etc/promtail/config.yml
Create loki-config.yaml and promtail-config.yaml
Configure Loki and Promtail for log collection.
Monitoring Model Performance (Advanced)
For machine learning models, you might also want to monitor:
- Prediction Distributions: Track the distribution of predicted classes or probabilities.
- Data Drift: Identify if input data distributions change over time.
- Model Drift: Detect changes in model performance.
Implement Custom Metrics
Modify your application to collect custom metrics:
# Example: Counter for predicted classes
PREDICTED_SURVIVED = Counter('predicted_survived_total', 'Total predictions of survived')
PREDICTED_NOT_SURVIVED = Counter('predicted_not_survived_total', 'Total predictions of not survived')
@app.get("/predict")
def predict():
# Example prediction logic
prediction = model.predict(some_input_data)
if prediction == 1:
PREDICTED_SURVIVED.inc()
else:
PREDICTED_NOT_SURVIVED.inc()
return {"prediction": prediction}
You can then visualize these metrics in Grafana.
Summary
By integrating these open-source tools, you've added robust observability features to your project:
- Prometheus collects metrics.
- Grafana visualizes metrics and logs.
- Jaeger provides distributed tracing.
- OpenTelemetry standardizes the instrumentation of your application.
- Docker Compose orchestrates all services.
This setup enables you to monitor the health and performance of your application comprehensively.
References
Next Steps
- Security: Ensure that your metrics and tracing endpoints are secured in a production environment.
- Scaling: If you scale your application, consider using tools like Kubernetes for orchestration.
- Alerts: Set up alerts in Prometheus or Grafana to notify you when certain thresholds are crossed.
- Extend Instrumentation: Instrument more parts of your code to capture detailed metrics and traces.
By following these steps, you've successfully added observability to your Titanic ML project using open-source tools and Docker.