New Relic - Custom Attributes in Drupal

New Relic is an excellent tool for improving and monitoring your Drupal installation however there are some atributes that are not available out of the box and require the creation of custom attributes. Here we will give a quick overview of how to do this.

Using New Relic

New Relic will caputure all sorts of useful information about your drupal installation so that you can find out where bottlenecks are and hopefully whats causng them. However for one of our clients we also needed to know the ip the request originated from and also which user was making the request at the time.

Out of the box New Relic doesn't capture the request ip nor obviously drupal specific information such as the user id or name. It does however allow you to create custom attributes and custom events to make specific data available.

Report custom events and attributes

Capturing the information

The information we want to caputre is relatively straightforward and how to do it is explained here

newrelic_add_custom_parameter (PHP agent API)

so for the request ip we used

newrelic_add_custom_parameter ("request_ip", $_SERVER['REMOTE_ADDR']);

and for the user name and ip we used

newrelic_add_custom_parameter("user_name", \Drupal::currentUser()->getAccountName());

The trickier part was where in the order of a request would you be able to do this reliably. This is where we made use of drupal services and listening for an event. For the ip we needed  the http_middleware.page_cache  and used the following resource to help ensure it was called in the proper order.

Replacing hook_boot and hook_init Functionality in Drupal 8

For the user name we had to listen to the <?phpAccountEvents::SET_USER?>

This event allows modules to perform an action whenever the current user is set. The event listener receives an \Drupal\Core\Session\AccountSetEvent instance. The event is fired when Drupal initializes the user object for the current request.

Deploying the solution

We created a custom module to capture this data and once the module was enabled the new attributes became available on New Relic.