---
title: "Profile Drush Commands in New Relic"
date: "2024-02-16T03:40:21+00:00"
summary: "Learn to profile Drush commands in New Relic for better Drupal performance monitoring. Step-by-step guide for setup and configuration."
image:
type: "page"
url: "/acquia-cloud-platform/profile-drush-commands-new-relic"
id: "01991325-f2a4-4e3c-ad38-a0e5e710956e"
---

To profile the performance of [Drush](https://www.drush.org) commands used in [scheduled jobs](/acquia-cloud-platform/using-scheduled-jobs-support-your-application "Using scheduled jobs to support your application") through [New Relic’s transactions](https://docs.newrelic.com/docs/apm/transactions/intro-transactions/transactions-new-relic-apm/):

1.  [Setting up the New Relic PHP Agent configuration for Drush](#setting-up-the-new-relic-php-agent)
2.  [Optional: Configuring Drupal to define the Transaction Name](#configurng-drupal-transaction-name)
3.  [Optional: Creating a script to run Drush cron and generate a NR transaction trace](#creating-script-run-drush-commands)
4.  [Inspecting Drush transaction traces in New Relic](#verifying-drush-commands)

Important

These steps are applicable for current Drupal and current Drush versions. Use these steps for earlier versions of Drupal that use Drush 9 as a minimum. Cloud Platform recommends that you use the latest Drupal and Drush versions. You cannot enable profiling for Drush 9 or earlier.

Setting up the New Relic PHP Agent configuration for Drush
----------------------------------------------------------

To ensure that Drush invocations generate a transaction trace in New Relic, you must provide special configuration. Create a `drush.ini` file to use during Drush invocations.

In that file, use the following [New Relic configuration file variables](https://docs.newrelic.com/docs/apm/agents/php-agent/configuration/php-agent-configuration/#inivar-background):

Variable name

Description

Required

Example

`newrelic.license`

Indicates the New Relic license key installed in Cloud Platform.

Only if undefined or overriding current value.

`"a47b28d4db93f9476e3f9576352061a20452NRAL"`

`newrelic.appname`

Indicates the New Relic application name that data reports under.

Only if undefined or overriding current value.

`"myapplication.dev"`

`newrelic.enabled`

Indicates if the New Relic agent is enabled or disabled.

Yes

`true`

`newrelic.transaction_tracer.threshold`

Minimum response time a transaction must exceed to be captured as a detailed trace.

Yes. Set value to be less than the execution time of any drush commands you want to run. Set to `1ms` to trigger every time.

`1ms`

To decide if any values require overrides, obtain the platform default values by running the `php -i |fgrep "newrelic."` command in an Cloud Platform SSH session.

Create the file `drush.ini` file in your home directory,`/home/clouduser/.drush`. If this file already exists, add the content at the end of the file. Ensure that you include the quote character (") in the appropriate values.

Example contents of the `drush.ini` file:

    ; Remove next line if PHP complains that extension is already loaded.
    extension=newrelic.so
    ; Optional variables, may already be configured.
    newrelic.license = "[INSERT LICENSE KEY HERE]"
    newrelic.appname = "[site].[env]"
    ; These are required for Drush.
    newrelic.enabled = true
    newrelic.transaction_tracer.threshold = 1ms

After you create this file, generate a New Relic transaction trace by running a Drush command that exceeds the threshold value. Prefix Drush runs with the following syntax:

 `PHP_INI_SCAN_DIR=:$HOME/.drush [space] drush [drush-command-and-arguments-here]`  

Example:

    
    PHP_INI_SCAN_DIR=:$HOME/.drush drush cron

It can take a few minutes before the transaction trace appears in New Relic.

Optional: Configuring Drupal to define the Transaction Name
-----------------------------------------------------------

By default, New Relic displays transactions for Drush runs with the name PHP Command Line. To ensure New Relic displays the specific Drush command that executed, you must update the settings.php file of the Drupal site. For more information, visit [New Relic PHP agent API](https://docs.newrelic.com/docs/apm/agents/php-agent/php-agent-api/guide-using-php-agent-api/) and [newrelic\_name\_transaction](https://docs.newrelic.com/docs/apm/agents/php-agent/php-agent-api/newrelic_name_transaction/).

In your codebase, add the following code snippet to the Drupal site’s `settings.php` file.

    // If this is a CLI call, set some parameters so that
    // it can be logged to New Relic
    if (PHP_SAPI === 'cli') {
      $cli_arg = NULL;
    
      $_SERVER['REQUEST_METHOD'] = 'CLI';
    
      // If we are in a drush environment, set the REQUEST_URI to the command.
      try {
        // Check if we have the \Drush\Drush::input() method - that is we expect to use a later Drush version
    
        $method = new ReflectionMethod('\Drush\Drush::input');
    
        if ( $method->isStatic() )
        {
            // Method exists!
            // Retrieve the drush command and set New Relic transaction name
            $cli_arg = \Drush\Drush::input()->getFirstArgument();
            $_SERVER['REQUEST_URI'] = $cli_arg;
    
            if (extension_loaded('newrelic')) {
              // Using the function newrelic_name_transaction()
              // <https://docs.newrelic.com/docs/apm/agents/php-agent/php-agent-api/newrelic_name_transaction/>
              if (function_exists('newrelic_name_transaction') && !empty($cli_arg)) {
                $cli_arg = 'drush ' . $cli_arg;
    
                // Define the Transaction Name for New Relic
                newrelic_name_transaction($cli_arg);
              }
            }
        }
      }
      catch ( ReflectionException $e )
      {
          // The method \Drush\Drush::input() method does not exist
          // We will do nothing, so as to allow rest of script to continue
      }
    }

Optional: Creating a script to run Drush cron and generate a NR transaction trace
---------------------------------------------------------------------------------

You can create a script that runs Drush cron and captures its transaction trace to New Relic. You can add this script to the application’s scheduled jobs.

The following steps serve as an example. You must modify the steps based on your application needs.

1.  In your codebase, create the Shell script at `<code_base_root>/scripts/newrelic_drush_cron.sh` with the following content:
    
        #!/usr/bin/env bash 
        # newrelic_drush_cron.sh
        #   Sends a transaction trace to New Relic
        #   Requires a $HOME/.drush/drush.ini file with New Relic configuration.
        #   Provided as-is as example code.
        
        if [[ $# -ne 2 ]]; then 
            echo "Script requires two parameters" >&2 
            echo "${0} AH_SITE_NAME SITE_DOMAIN" >&2 
            exit 2 
        fi 
        
        logfile="/shared/logs/newrelic_drush_cron.log" 
        exec > >(/usr/bin/tee -a "$logfile") 2>&1 
        if [ -n "${2}" ]; then 
          uri="${2}" 
        else 
          uri="${AH_SITE_NAME}.${AH_REALM}.acquia-sites.com" 
        fi 
        
        #echo "URI: ${uri}" 
        echo "***** Script ${0} Started: $(date --rfc-3339=seconds) *****" 
        
        echo "***** Running Drush status" 
        drush --root="/var/www/html/${AH_SITE_NAME}/docroot/" --uri="${uri}" status 2>&1
        echo 
        
        echo "***** Running Drush cron"
        
        # The PHP_INI_SCAN_DIR loads any PHP *.ini files from the $HOME/.drush folder. 
        # The awk command adds timestamps to each line output by Drush.
        PHP_INI_SCAN_DIR=:$HOME/.drush drush --root="/var/www/html/${AH_SITE_NAME}/docroot/" --uri="${uri}" cron 2>&1 | awk '{print "["strftime("%Y-%m-%d %H:%M:%S %Z")"] "$0;fflush()}'
        
        echo 
        
        echo -e "***** Script Completed: $(date --rfc-3339=seconds) *****\\n"
    
2.  Ensure that script permissions are executable.
    
        chmod +x [code_base_root]/scripts/newrelic_drush_cron.sh
    
3.  Test the script on the SSH session within a Cloud Platform's non-production environment. For example, 
    
        /var/www/html/myapplication.dev/scripts/newrelic_drush_cron.sh myapplicationdev https://myapplicationdev.prod.acquia-sites.com
    
4.  Confirm that the`/shared/logs/newrelic_drush_cron.log` file has an entry that starts with a line similar to:
    
        ***** Script /var/www/html/myapplication.dev/scripts/newrelic_drush_cron.sh Started: 2024-08-08 09:55:44+00:00 *****
    
5.  After the script is ready, add a scheduled job to the Cloud Platform environment to run the script at regular intervals. For more information, visit [Creating scheduled jobs](https://docs.acquia.com/acquia-cloud-platform/manage-apps/cron#section-creating-scheduled-jobs).

    /var/www/html/scripts/newrelic_drush_cron.sh myapplicationdev https://myapplicationdev.prod.acquia-sites.com

Inspecting Drush transaction traces in New Relic
------------------------------------------------

To review Drush transaction traces in New Relic:

1.  Navigate to the APM page for the application name.
    
2.  Select ****Transactions****.
    
3.  Select ****Transaction Type**** and set it to ****Non-web****. If this option is not visible, reload the New Relic page after you run the Drush command.
    
4.  Explore ****Transaction traces**** and locate the trace for the Drush commands.