How to ignore certain endpoints in NewRelic APM in Django?
The best way to ignore certain endpoints/api from NewRelic APM would be to tweak the NewRelic agent flag using a middleware
from newrelic import agent
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Check if the current url needs to be ignored or not.
if ignore_newrelic_transaction(request.path_info):
# Read more about how to ignore transactions in new relic.
# https://docs.newrelic.com/docs/agents/python-agent/python-agent-api/ignoretransaction-python-agent-api/
agent.ignore_transaction(flag=True)
"""
From here the current middleware request is sent to the next middleware
"""
response = self.get_response(request)
return response
def ignore_newrelic_transaction(req_url):
""" You can write different logic as per your requirement, currently I am using only for a certain endpoint, but if you want to incorporate it for multiple endpoints then you can implement the logic for list of api endpoints.
"""
if req_url.startswith("/v1/ignore-url"):
return True
.....
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"custom_middleware.CustomMiddleware", # add this line
]
.....
The details of how to configure new relic agent is mentioned in this doc
Basically what we are doing in the custom_middleware.py
file
- Create a new middleware
CustomMiddleware
- In the custom middleware check if the requested url is to be ignored or not.
- If the requested url is to be ignored, then set the flag
agent.ignore_transaction(flag=True)
- So this whole transaction would now be ignored from the new relic monitoring, no data would be captured for the particular request.
If you are looking to integrate NewRelic to your existing Django Application then follow this guide.
When should we use this feature?
This should be used for health checks, so that the overall response time and Apdex score of the application is not impacted by slow response time. In general if you have celery added to your Django application then you will notice that the health-check for your application will have higher response time, this might bring down your overall Apdex score, so I would advice to ignore any health-check monitoring from NewRelic.
If you want to learn how to add health check to your system monitoring, you can follow my blog