Tracing PHP Applications
Security Monitoring is now available Security Monitoring is now available

Tracing PHP Applications

Installation and Getting Started

If you already have a Datadog account you can find step-by-step instructions in our in-app guides for either host-based or container-based set ups.

For descriptions of terminology used in APM, take a look at the official documentation.

For details about open-source contributions to the PHP tracer, refer to the contributing guide.

Setup the Datadog Agent

The PHP APM tracer sends trace data through the Datadog Agent.

Install and configure the Datadog Agent. See the additional documentation for tracing Docker applications or Kubernetes applications.

For Agent version 7.18.0 and above, APM is enabled by default for all environments without further action. If you are running an older version of the agent, make sure the Agent has APM enabled.

Install the extension

Install the PHP extension using one of the precompiled packages for supported distributions.

Once downloaded, install the package with one of the commands below.

# using RPM package (RHEL/Centos 6+, Fedora 20+)
rpm -ivh datadog-php-tracer.rpm

# using DEB package (Debian Jessie+ , Ubuntu 14.04+ on supported PHP versions)
dpkg -i datadog-php-tracer.deb

# using APK package (Alpine)
apk add datadog-php-tracer.apk --allow-untrusted

The extension will be installed for the default PHP version. To install the extension for a specific PHP version, use the DD_TRACE_PHP_BIN environment variable to set the location of the target PHP binary before installing.

export DD_TRACE_PHP_BIN=$(which php-fpm7)

Restart PHP (PHP-FPM or the Apache SAPI) and then visit a tracing-enabled endpoint of your application. View the APM UI to see the traces.

Note: It might take a few minutes before traces appear in the UI. If traces still do not appear after a few minutes, run the dd-doctor.php diagnostic script from the host machine to help identify any issues.

If you can’t find your distribution, you can manually install the PHP extension.

Automatic Instrumentation

Tracing is automatically enabled by default. Once the extension is installed, ddtrace traces your application and sends traces to the Agent.

Datadog supports all web frameworks out of the box. Automatic instrumentation works by modifying PHP’s runtime to wrap certain functions and methods to trace them. The PHP tracer supports automatic instrumentation for several libraries.

Automatic instrumentation captures:

  • Method execution time
  • Relevant trace data, such as URL and status response codes for web requests or SQL queries for database access
  • Unhandled exceptions, including stacktraces if available
  • A total count of traces (e.g., web requests) flowing through the system

Note: If your application does not use Composer nor an autoloader registered with spl_autoload_register(), set the environment variable, DD_TRACE_NO_AUTOLOADER=true, to enable automatic instrumentation.

Change Agent Hostname

Configure your application level tracers to submit traces to a custom Agent hostname:

The PHP tracer automatically looks for and initializes with the ENV variables DD_AGENT_HOST and DD_TRACE_AGENT_PORT.

See tracer configuration for more information on how to set these variables.

Compatibility

PHP APM supports the following PHP versions:

VersionSupport type
7.4.xFully Supported
7.3.xFully Supported
7.2.xFully Supported
7.1.xFully Supported
7.0.xFully Supported
5.6.xFully Supported
5.4.xFully Supported

PHP APM supports the following SAPI’s:

SAPISupport type
apache2handlerFully Supported
cliFully Supported
fpm-fcgiFully Supported
cgi-fcgiFully Supported

Integrations

Web Framework Compatibility

By default Datadog supports all PHP web frameworks out of the box, which allows you to see traces for spans of supported libraries—for example: database and HTTP clients.

The following table enumerates some of the frameworks and versions Datadog succesfully traces.

Web frameworks:

ModuleVersionsSupport Type
CakePHP2.xAll supported PHP versions
CodeIgniter2.x, 3.xPHP 7+
Laravel4.2, 5.x, 6.xAll supported PHP versions
Lumen5.2+All supported PHP versions
Slim3.xAll supported PHP versions
Symfony3.3, 3.4, 4.xAll supported PHP versions
WordPress4.x, 5.xPHP 7+
Zend Framework1.12All supported PHP versions
Yii1.1, 2.0All supported PHP versions
DrupalAll supported PHP versions
Magento2All supported PHP versions
Phalcon1.3, 3.4All supported PHP versions
Slim2.xAll supported PHP versions
Neos Flow1.1All supported PHP versions
FuelPHP1.1PHP 7+

Note that even if you don’t see your web framework in this list, it is supported out of the box with the latest release of the tracer.

Want to see more span metadata and framework internals? Datadog is continously adding more support for in-depth tracing for PHP web-frameworks. Check with the Datadog team for help.

CLI Library Compatibility

Tracing from the CLI SAPI is disabled by default. To enable tracing of PHP CLI scripts, set DD_TRACE_CLI_ENABLED=true.

ModuleVersionsSupport Type
CakePHP Console2.xFully Supported
Laravel Artisan5.xFully Supported
Symfony ConsoleComing Soon

Don’t see your desired CLI library? Datadog is continually adding additional support. Check with the Datadog team for help.

Datastore Compatibility

ModuleVersionsSupport Type
Amazon RDS (using PDO or MySQLi)(Any Supported PHP)Fully Supported
Elasticsearch1.xFully Supported
EloquentLaravel supported versionsFully Supported
Memcached(Any Supported PHP)Fully Supported
MongoDB1.4.xFully Supported
MySQLi(Any Supported PHP)Fully Supported
PDO (MySQL, PostgreSQL, MariaDB)(Any Supported PHP)Fully Supported
Predis1.1Fully Supported
AWS CouchbaseAWS PHP SDK 3Coming Soon
AWS DynamoDBAWS PHP SDK 3Coming Soon
AWS ElastiCacheAWS PHP SDK 3Coming Soon
Doctrine ORM2Coming Soon
ODBC(Any Supported PHP)Coming Soon
PHPredis4Coming Soon
Solarium4.2Coming Soon

Don’t see your desired datastores? Datadog is continually adding additional support. Check with the Datadog team for help.

Library Compatibility

ModuleVersionsSupport Type
Curl(Any Supported PHP)Fully Supported
Guzzle5.xFully Supported
Guzzle6.xFully Supported
BeanstalkdComing Soon
ReactPHPComing Soon

Don’t see your desired libraries? Datadog is continually adding additional support. Check with the Datadog team for help.

Configuration

The PHP tracer can be configured using environment variables.

Note: If you use code auto-instrumentation (the recommended approach) be aware that the instrumenting code is executed before any user code. As a result, the environment variables below must be set at the server level and be available to the PHP runtime before any user code is executed. For example, putenv() and .env files would not work.

Apache

For Apache with php-fpm, use the env directory in your www.conf configuration file to configure the php tracer, for example:

env[DD_AGENT_HOST] = $FROM_HOST_ENV
env[DD_TRACE_DEBUG] = true

Alternatively, you can use SetEnv from the server config, virtual host, directory, or .htaccess file.

SetEnv DD_TRACE_DEBUG true

NGINX

For NGINX, use the env directory in the php-fpm’s www.conf file, for example:

env[DD_AGENT_HOST] = $FROM_HOST_ENV
env[DD_TRACE_DEBUG] = true

PHP CLI server

Set in the command line to start the server.

DD_TRACE_DEBUG=true php -S localhost:8888

Environment Variable Configuration

Env variableDefaultNote
DD_AGENT_HOSTlocalhostThe Agent host name
DD_AUTOFINISH_SPANSfalseWhether spans are automatically finished when the tracer is flushed
DD_DISTRIBUTED_TRACINGtrueWhether to enable distributed tracing
DD_INTEGRATIONS_DISABLEDnullA CSV list of integrations to disable, for example: curl,mysqli (see Integration names).
DD_PRIORITY_SAMPLINGtrueWhether to enable priority sampling
DD_SERVICE_NAMEnullThe default app name
DD_SERVICE_MAPPINGnullChange the default name of an APM integration. Rename one or more integrations at a time, for example: DD_SERVICE_MAPPING=pdo:payments-db,mysqli:orders-db (see Integration names).
DD_TRACE_AGENT_ATTEMPT_RETRY_TIME_MSEC5000IPC-based configurable circuit breaker retry time (in milliseconds)
DD_TRACE_AGENT_CONNECT_TIMEOUT100Maximum time the allowed for Agent connection setup (in milliseconds)
DD_TRACE_AGENT_CONNECT_TIMEOUT100The Agent connection timeout (in milliseconds)
DD_TRACE_AGENT_MAX_CONSECUTIVE_FAILURES3IPC-based configurable circuit breaker max consecutive failures
DD_TRACE_AGENT_PORT8126The Agent port number
DD_TRACE_AGENT_TIMEOUT500The Agent request transfer timeout (in milliseconds)
DD_TRACE_ANALYTICS_ENABLEDfalseFlag to enable app analytics for relevant spans in web integrations
DD_TRACE_AUTO_FLUSH_ENABLEDfalseAutomatically flush the tracer when all the spans are closed; set to true in conjunction with DD_TRACE_GENERATE_ROOT_SPAN=0 to trace long-running processes
DD_TRACE_CLI_ENABLEDfalseEnable tracing of PHP scripts from the CLI
DD_TRACE_DEBUGfalseEnable debug mode for the tracer
DD_TRACE_ENABLEDtrueEnable the tracer globally
DD_TRACE_GENERATE_ROOT_SPANtrueAutomatically generate a top-level span; set to false in conjunction with DD_TRACE_AUTO_FLUSH_ENABLED=1 to trace long-running processes
DD_TRACE_GLOBAL_TAGSnullTags to be set on all spans, for example: key1:value1,key2:value2.
DD_TRACE_HTTP_CLIENT_SPLIT_BY_DOMAINfalseSet the service name of HTTP requests to host-<hostname>, for example a curl_exec() call to https://datadoghq.com has the service name host-datadoghq.com instead of the default service name of curl.
DD_TRACE_MEASURE_COMPILE_TIMEtrueRecord the compile time of the request (in milliseconds) onto the top-level span
DD_TRACE_NO_AUTOLOADERfalseSet to true to enable auto instrumentation for applications that do not use an autoloader
DD_TRACE_REPORT_HOSTNAMEfalseEnable hostname reporting on the root span
DD_TRACE_RESOURCE_URI_MAPPINGnullCSV of URL-to-resource-name mapping rules, for example: /foo/*,/bar/$*/baz (see “Custom URL-To-Resource Mapping”)
DD_TRACE_SAMPLE_RATE1.0The sampling rate for the traces (defaults to: between 0.0 and 1.0). For versions <0.36.0, this parameter is DD_SAMPLING_RATE.
DD_TRACE_SAMPLING_RULESnullA JSON encoded string to configure the sampling rate. Examples: Set the sample rate to 20%: [{"sample_rate": 0.2}]. Set the sample rate to 10% for services starting with ‘a’ and span name ‘b’ and set the sample rate to 20% for all other services: [{"service": "a.*", "name": "b", "sample_rate": 0.1}, {"sample_rate": 0.2}] (see Integration names).
DD_TRACE_URL_AS_RESOURCE_NAMES_ENABLEDtrueEnable URL’s as resource names (see Map resource names to normalized URI).
DD_<INTEGRATION>_ANALYTICS_ENABLEDfalseA flag to enable app analytics for relevant spans in a specific integration (see Integration names).
DD_<INTEGRATION>_ANALYTICS_SAMPLE_RATE1.0Set the app analytics sample rate for relevant spans in a specific integration (see Integration names).

Integration names

The table below specifies the default service names for each integration. Change the service names with DD_SERVICE_MAPPING.

Use the name when setting integration-specific configuration such as, DD_<INTEGRATION>_ANALYTICS_ENABLED, for example: Laravel is DD_LARAVEL_ANALYTICS_ENABLED.

IntegrationService Name
CakePHPcakephp
CodeIgnitercodeigniter
cURLcurl
ElasticSearchelasticsearch
Eloquenteloquent
Guzzleguzzle
Laravellaravel
Lumenlumen
Memcachedmemcached
Mongomongo
Mysqlimysqli
PDOpdo
Predispredis
Slimslim
Symfonysymfony
WordPresswordpress
Yiiyii
ZendFrameworkzendframework

Map resource names to normalized URI

By default, the URL is used to form the trace resource name in the format <HTTP_REQUEST_METHOD> <NORMALIZED_URL>, with the query string removed from the URL. This allows better visibility in any custom framework that is not automatically instrumented by normalizing the URLs and grouping together generic endpoints under one resource.

HTTP RequestResource Name
GET request to /foo?a=1&b=2GET /foo
POST request to /bar?foo=barPOST /bar

Numeric IDs, UUIDs (with and without dashes), and 32-to-512-bit hexadecimal hashes are automatically replaced with a ? character.

URL (GET request)Resource Name
/user/123/showGET /user/?/show
/widget/b7a992e0-3300-4030-8617-84553b11c993GET /widget/?
/api/v2/b7a992e033004030861784553b11c993/123GET /api/v2/?/?
/book/0dbf3596GET /book/?

You can turn this functionality OFF using DD_TRACE_URL_AS_RESOURCE_NAMES_ENABLED=false.

Custom URL-To-Resource Mapping

When URL resource names are enabled, custom URL mapping is configured via DD_TRACE_RESOURCE_URI_MAPPING which accepts a CSV list of mapping rules. The wildcards * and $* are supported, so DD_TRACE_RESOURCE_URI_MAPPING=/foo/*,/bar/$*/baz. In this context, * is a greedy match with a replacement character ?, and $* performs a greedy match without replacement

Rules are applied in the same order as they appear in DD_TRACE_RESOURCE_URI_MAPPING. Less greedy rules should appear in the list before more greedy rules, e.g. /foo/$*/bar,/foo/*

The * wildcard is replaced with ?.

Mapping RuleURL (GET request)Resource Name
/foo/*/foo/barGET /foo/?
/foo/*/bar/foo/baz/faz/barGET /foo/?/bar
/foo-*-bar/foo-secret-barGET /foo-?-bar

The $* wildcard matches without replacement.

Mapping RuleURL (GET request)Resource Name
/state/$*/show/state/kentucky/showGET /state/kentucky/show
/widget/*/type/$*/widget/foo-id/type/greenGET /widget/?/type/green

Upgrading

To upgrade the PHP tracer, download the latest release and follow the same steps as installing the extension.

Note: If you are using second level caching in OPcache by setting the parameter opcache.file_cache, remove the cache folder.

Removing

To remove the PHP tracer:

  1. For php-fpm, stop the php-fpm service, otherwise stop the Apache web server.
  2. Unlink files 98-ddtrace.ini and 99-ddtrace-custom.ini from your php configuration folder.
  3. For php-fpm, restart php-fpm service, otherwise restart the Apache web server.

Note: If you are using second level caching in OPcache by setting the parameter opcache.file_cache, remove the cache folder.

Further Reading