Integrating New Relic with FastAPI Applications
New Relic is a powerful application performance monitoring (APM) tool that helps developers monitor, debug, and optimize their applications. In this guide, we'll walk through the process of integrating New Relic with your FastAPI application.
Prerequisites
Before we begin, make sure you have:
- A FastAPI application up and running
- A New Relic account (free tier available)
- Python 3.7 or higher installed
Installation
First, install the New Relic Python agent:
pip install newrelic
Configuration
1. Get Your License Key
- Log in to your New Relic account
- Go to Account Settings > API keys
- Copy your license key
2. Create New Relic Configuration File
Create a file named newrelic.ini
in your project root:
[newrelic]
license_key = your_license_key_here
app_name = your_fastapi_app_name
monitor_mode = true
log_level = info
ssl = true
high_security = false
transaction_tracer.enabled = true
transaction_tracer.transaction_threshold = apdex_f
transaction_tracer.record_sql = obfuscated
transaction_tracer.stack_trace_threshold = 0.5
transaction_tracer.explain_enabled = true
transaction_tracer.explain_threshold = 0.5
Integration with FastAPI
Update your FastAPI application code:
import newrelic.agent
newrelic.agent.initialize('newrelic.ini')
from fastapi import FastAPI
app = FastAPI()
# Middleware to track requests
@app.middleware("http")
async def add_new_relic_transaction(request, call_next):
transaction = newrelic.agent.current_transaction()
if transaction:
transaction.name = f"{request.method} {request.url.path}"
response = await call_next(request)
return response
@app.get("/")
async def root():
return {"message": "Hello World"}
Custom Monitoring
Track Custom Metrics
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# Record custom metric
newrelic.agent.record_custom_metric('custom/user_requests', 1)
# Your user fetching logic here
return {"user_id": user_id}
Error Tracking
@app.get("/items/{item_id}")
async def get_item(item_id: int):
try:
# Your item fetching logic here
if not item:
raise ValueError("Item not found")
except Exception as e:
# Report error to New Relic
newrelic.agent.notice_error()
raise HTTPException(status_code=404, detail="Item not found")
Running Your Application
Start your application with the New Relic agent:
newrelic-admin run-program uvicorn main:app --reload
Monitoring in New Relic
After deployment, you can monitor your application in New Relic:
- Application Overview: View general performance metrics
- Transaction Traces: Analyze slow requests
- Error Analytics: Track and debug errors
- Custom Dashboards: Create custom views for your metrics
Best Practices
- Environment Variables: Store your New Relic license key as an environment variable
- Custom Naming: Use meaningful names for custom metrics
- Error Handling: Implement proper error tracking
- Performance Monitoring: Set up alerts for performance thresholds
Conclusion
New Relic integration with FastAPI provides powerful monitoring capabilities that help you:
- Track application performance
- Monitor error rates
- Analyze slow transactions
- Create custom metrics
- Set up alerts
With this setup, you'll have comprehensive insights into your FastAPI application's performance and behavior in production.