How to add User IP address to NewRelic transaction for Django?
NewRelic out of the box would ignore collecting User IP, due to privacy concerns. But for a lot of web applications, it is important to capture user IP so that performance can be monitored by categorizing by different physical user IPs.
To pass user IP to a transaction of the trace object of NewRelic, you should implement a custom middleware and add the user IP detection code. If you don't know how to write custom middleware, then head to the below blog.
Here the get_client_ip
function is extracting the IP address from the request header and returning back. Please check before hand whether the IP address returned from this function is the correct user IP. Since modern web applications have multiple layers, like ALB, API Gateway, etc, so it might be possible the IP added to the header is in a different position to what I have added in the given example.
Once the IP address is extracted, we are appending the property using newrelic.agent
SDK. You can modify the name ClientIpAddress
to any desired name which you want, just make sure to not give space.
agent.add_custom_parameters([("ClientIpAddress", get_client_ip(request))])
The above integration would now be sending the User IP for every transaction and one can write queries to identify them. Go to the query builder and run the below query to see your captured user IP address
SELECT ClientIpAddress FROM Transaction WHERE entityGuid = <your application> SINCE 30 MINUTES AGO
If you are not aware of how to integrate NewRelic into your Django application you can follow the below blog