Sub topic 13
Logging and monitoring predictions
This chapter assumes you have the FastAPI service from the earlier chapters, with main.py, the /predict endpoint, and a model loaded at startup. It also assumes you know Python's logging module at a basic level.
Why a working API still needs logs
A model service can return HTTP 200 and still be wrong. The model may be slow, or it may receive inputs unlike its training data. Nothing crashes in either case. Logs and metrics are how you notice.
Two terms are used throughout:
- A log is a record of one event, such as one prediction request.
- A metric is a number aggregated over time, such as the 95th percentile latency over the last five minutes.
Logs help you debug a single request. Metrics help you see trends and set alerts.
Logging each prediction
Use structured logs, meaning one JSON object per line. Log aggregation tools can parse JSON without custom rules. Add a request ID so you can match a log line to a client complaint, and measure how long the model call takes.
Change the top of main.py and replace the /predict function:
import json
import logging
import time
import uuid
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("inference")
@app.post("/predict", response_model=Prediction)
def predict(features: IrisFeatures):
request_id = str(uuid.uuid4())
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
start = time.perf_counter()
prediction = int(models["iris"].predict(row)[0])
latency_ms = (time.perf_counter() - start) * 1000
logger.info(json.dumps({
"event": "prediction",
"request_id": request_id,
"model": "iris",
"class_index": prediction,
"latency_ms": round(latency_ms, 2),
}))
return Prediction(class_index=prediction)Each call now prints a line like {"event": "prediction", "request_id": "...", "class_index": 0, "latency_ms": 1.8}.
What to monitor
| Signal | What it tells you | Typical alert |
|---|---|---|
| Request rate | Traffic level | Sudden drop to zero |
| Latency (p50, p95, p99) | Speed seen by callers | p95 above your target |
| Error rate (4xx, 5xx) | Bad inputs or broken service | 5xx above 1% |
| Prediction distribution | Share of each class returned | One class suddenly dominates |
| Input distribution | Feature ranges and averages | Values far from training data |
Use percentiles rather than averages for latency. An average hides the slow requests that users notice.
The last two rows catch drift, which means live data slowly stops resembling training data. The service stays healthy, but accuracy falls. If all your predictions suddenly become class 2, the input data probably changed. You can't measure accuracy directly without true labels, which usually arrive later. Until they do, watch the distributions.
Common mistakes
- Logging with
print. You lose levels, timestamps, and the ability to route output. - Logging inside the model call without the request ID. You can't tie a slow prediction to a request.
- Putting high-variety values, such as raw feature values, in metric labels. This creates huge numbers of time series and slows your monitoring system.
- Alerting only on crashes. The failures described above produce no crash.
Exercise
Your service has p95 latency within target and a 0% error rate, but the share of predictions returning class 2 rose from 30% to 90% overnight. Which signal caught this, and what is the most likely cause to investigate first?
Show answer
The prediction distribution signal caught it. Investigate input drift first: check whether the incoming feature values (or an upstream data source or unit change) differ from the training data. A code or infrastructure fault is less likely because latency and errors look normal.