- Install the required packages:
pip install fastapi uvicorn kubernetes python-dotenv
- Create a Kubernetes deployment YAML file for your FastAPI application. Here's an example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: fastapi-app
spec:
replicas: 1
selector:
matchLabels:
app: fastapi
template:
metadata:
labels:
app: fastapi
spec:
containers:
- name: fastapi
image: your-docker-image
ports:
- containerPort: 80
- Create a Kubernetes service YAML file to expose your FastAPI application. Here's an example:
apiVersion: v1
kind: Service
metadata:
name: fastapi-service
spec:
selector:
app: fastapi
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
- Deploy your FastAPI application to Kubernetes using the following commands:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
- Modify your FastAPI application to log inference requests and responses. Here's an example:
from fastapi import FastAPI, Request
import logging
import json
app = FastAPI()
# Set up logging
logging.basicConfig(filename='/app/logs/inference.log', level=logging.INFO, format='%(asctime)s - %(message)s')
@app.post("/inference")
async def inference(request: Request):
request_data = await request.json()
logging.info(f"Inference request: {json.dumps(request_data)}")
response = await perform_inference(request_data)
logging.info(f"Inference response: {json.dumps(response)}")
return response
async def perform_inference(data):
return {"result": "example result"}
@app.get("/inference/logs")
async def get_logs():
with open('/app/logs/inference.log', 'r') as file:
logs = file.read()
return {"logs": logs}
- Create a Kubernetes CronJob to periodically query your FastAPI application for inference logs. Here's an example:
apiVersion: batch/v1
kind: CronJob
metadata:
name: inference-logs
spec:
schedule: "0 */6 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: log-query
image: your-query-image # Ensure this image has log query script
command: ["python", "/scripts/query_logs.py"]
restartPolicy: OnFailure
- Create a Python script to query the inference logs and store them in a database or a file. Here's an example:
import requests
import json
# Configuration
url = "http://<your-service-ip>:<your-service-port>/inference/logs" # Replace with your IP and port
log_file_path = "/path/to/inference.log"
# Fetch logs from the FastAPI service
response = requests.get(url)
if response.status_code == 200:
logs = response.json()
# Write logs to a file
with open(log_file_path, 'w') as file:
json.dump(logs, file, indent=4)
else:
print(f"Failed to retrieve logs. Status code: {response.status_code}")
- Deploy the CronJob to Kubernetes using the following command:
kubectl apply -f cronjob.yaml
Now, your FastAPI application will log inference requests and responses, and the CronJob will periodically query the logs and store them in a file or a database.