PHP DataDog StatsD Client

Overview

PHP DataDog StatsD Client

CircleCI Author Packagist Version Total Downloads

This is an extremely simple PHP DogStatsD client.

Requires PHP >= 5.6.0.

See CHANGELOG.md for changes.

For a Laravel-specific implementation that wraps this library, check out laravel-datadog-helper.

Installation

Add the following to your composer.json:

"datadog/php-datadogstatsd": "1.5.*"

The first version shipped in composer is 0.0.3

Or manually clone this repository and set it up with require './src/DogStatsd.php'.

Once installed, turn on the socket extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.

Configuration

To instantiate a DogStatsd object using composer:



require __DIR__ . '/vendor/autoload.php';

use DataDog\DogStatsd;

$statsd = new DogStatsd(
    array('host' => '127.0.0.1',
          'port' => 8125,
     )
  );

DogStatsd constructor, takes a configuration array. See the full list of available DogStatsD Client instantiation parameters.

Origin detection over UDP in Kubernetes

Origin detection is a method to detect which pod DogStatsD packets are coming from in order to add the pod's tags to the tag list.

To enable origin detection over UDP, add the following lines to your application manifest

env:
  - name: DD_ENTITY_ID
    valueFrom:
      fieldRef:
        fieldPath: metadata.uid

The DogStatsD client attaches an internal tag, entity_id. The value of this tag is the content of the DD_ENTITY_ID environment variable, which is the pod’s UID. The agent uses this tag to infer packets' origin, and tag their metrics accordingly.

Usage

In order to use DogStatsD metrics, events, and Service Checks the Agent must be running and available.

Metrics

After the client is created, you can start sending custom metrics to Datadog. See the dedicated Metric Submission: DogStatsD documentation to see how to submit all supported metric types to Datadog with working code examples:

Some options are suppported when submitting metrics, like applying a Sample Rate to your metrics or tagging your metrics with your custom tags.

Events

After the client is created, you can start sending events to your Datadog Event Stream. See the dedicated Event Submission: DogStatsD documentation to see how to submit an event to your Datadog Event Stream.

Service Checks

After the client is created, you can start sending Service Checks to Datadog. See the dedicated Service Check Submission: DogStatsD documentation to see how to submit a Service Check to Datadog.

Roadmap

  • Add a configurable timeout for event submission via TCP
  • Write unit tests
  • Document service check functionality

Tests

composer test

Lint

composer lint

Fix lint

composer fix-lint
Comments
  • Add PHPCS, Clean up violations, Drop support for < PHP5.6

    Add PHPCS, Clean up violations, Drop support for < PHP5.6

    This PR cleans up docblocks and makes a couple formatting changes based on PSR1, PSR2, and PEAR coding standards. (PEAR changes limited to nicer formatting of docblocks.)

    EDIT: Updated this PR to also install PHPCS.

    EDIT: Updated this PR to drop support for PHP versions lower than 5.6.

    opened by timrourke 20
  • Fix: Use declared private fields

    Fix: Use declared private fields

    This PR

    • [x] uses declared private fields when assigning values in constructor

    πŸ’β€β™‚οΈ Running

    $ phpstan analyse --level=1 src
    

    yields

     2/2 [β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“] 100%
    
     ------ ---------------------------------------------------------------------------
      Line   src/DogStatsd.php
     ------ ---------------------------------------------------------------------------
      72     Access to an undefined property DataDog\DogStatsd::$apiCurlSslVerifyHost.
      73     Access to an undefined property DataDog\DogStatsd::$apiCurlSslVerifyPeer.
     ------ ---------------------------------------------------------------------------
    
    
     [ERROR] Found 2 errors
    
    opened by localheinz 8
  • submit to packagist.org

    submit to packagist.org

    Hello,

    I noticed you have a composer.json in your repo, but the package has not been submitted to packagist.org.

    It would be great if you can submit it, then it can be easily used as a composer package. http://packagist.org/packages/submit

    Or perhaps I am missing something?

    Thanks.

    opened by cornernote 8
  • Datadog increment/decrement not working

    Datadog increment/decrement not working

    is this function still working? Because I trying to use increment from example or by my self is not working. But the event function is working nicely.

    I try to use increment, but nothing happen to my metric

    opened by kevinralali 6
  • Support global tags, refactor internals of tag handling

    Support global tags, refactor internals of tag handling

    This takes the global_tags concept from the nodejs datadog library and adds equivalent support to the PHP library.

    It also refactors the internals of tag handling a bit, since there are currently three (!) different formats that constitute a valid tag. The output is unchanged, but it will now de-duplicate any repeated tags. If a tag has a different value in a direct metric vs the global one, it will apply the tag provided in the metric, replacing the global one.

    opened by Firehed 5
  • This doesn't appear to work in an nginx php-fpm setup.

    This doesn't appear to work in an nginx php-fpm setup.

    *725 FastCGI sent in stderr: "PHP message: PHP Fatal error: Class 'DataDogStatsD' not found in XXXXXXXX on line XXX"

    This despite the inclusion of the file require_once(...)

    Might it have something to do with socket?

    opened by recarv 5
  • Possible incompatibility with Datadog agent ( version 6 )

    Possible incompatibility with Datadog agent ( version 6 )

    Hi. I'm using this client and it's working fine with Datadog agent ( v5.22 ) but when I upgrade to Datadog v6, the timing metrics doesnt work.

    More details: PHP: 7.0 OS: Ubuntu 16

    Thanks in advance!

    opened by ghost 4
  • tags should be separated by comma only

    tags should be separated by comma only

    the implementation of tags in the client is inconsistent (and probably broken)

    the official dogstatsd states this:

    metric.name:value|type|@sample_rate|#tag1:value,tag2
    

    so tags are attached via # and separated via ,

    this implementation can be found in the ruby client for example.

    it looks like this is also implemented correctly for service-checks.

    but it looks like it's wrong in the metrics implementation as it will separate by ,#!

    /cc @bonko @fungusakafungus

    opened by phoet 4
  • Configurable UDP and TCP Events + cURL API Calls

    Configurable UDP and TCP Events + cURL API Calls

    Hello there!

    I am a very happy user of the PHP Datadog library that you've got here =)

    Currently I am on a project where we need to utilize the UDP events that are outlined here: http://docs.datadoghq.com/guides/dogstatsd/#events

    To utilize this I added the ability to send events via both UDP and TCP since I feel both are highly valuable in different scenarios (my companies use both). I have made UDP the default here so-as to just work "out of box" without needing an API configuration. If you call the "configure" method it is assumed you are utilizing the API. There are also a couple of cURL SSL configuration options that are important if folks are using self-signed certificates with reverse-proxies.

    I have also greatly improved the API events call by swapping out the "file_get_contents" strategy with a cURL one. This checks for things like response codes, empty bodies, malformed JSON, etc. to get down to checking the "status" field passed back by Datadog. If we want verification that our event went out (via TCP) we may as well ensure that the web request was properly handled =)

    I have kept in-line with your development practices to the best of my ability. If you wish to swap the default method for event communication from UDP to TCP let me know and I will re-submit a pull-request with that change.

    Otherwise thank you for your time in reviewing these improvements! They will make a HUGE difference in our adoption of this library =)

    Sincerely,

    • John Parks
    enhancement 
    opened by folkhack 4
  • Please look at the pull requests and merge or reject them.

    Please look at the pull requests and merge or reject them.

    At least the pwillcode one which fixes the composer package psr-0 autoloading. I am using that fork in production now specifically because of the autoloading.

    Thanks.

    opened by iparq 4
  • Add unit tests

    Add unit tests

    This PR installs and configures PHPUnit. In addition, it adds unit tests.

    Thanks, looking forward to your feedback!

    EDIT: I am now running PHPUnit tests in Travis. However, in order to support versions of PHP all the way back to PHP 5.3, I installed a rather old version of PHPUnit. This isn't ideal; some code in the older version of PHPUnit calls deprecated functions. See https://travis-ci.org/DataDog/php-datadogstatsd/jobs/423273440 for an example of the deprecation warnings.

    If those deprecation warnings seem problematic, PHPUnit could be upgraded to a more recent version (say, to 5.7.x, which supports PHP5.6+), and then Travis failures could be suppressed on a per-version basis. For example: https://github.com/sebastianbergmann/phpunit/blob/master/.travis.yml#L16

    opened by timrourke 3
  • Incompatible with upcoming PHP 8.2 release

    Incompatible with upcoming PHP 8.2 release

    Due to its heavy use of dynamically-declared properties, DogStatsd is largely incompatible with PHP 8.2 and will throw quite a few deprecation notices. Now might be a good opportunity to give this library some much-needed love.

    opened by Zenexer 1
  • push to dogstatsd in openmetrics format

    push to dogstatsd in openmetrics format

    We are using php with swooole - which automatically exposes swoole metrics in php array, json and openmetrics format.

    https://openswoole.com/article/openswoole-4.9.0-released

    I know there is an openmetrics integration for datatadog agent. The drawback - in that case I would have to add separate datadog agent container into ecs fargate task and configure it with openmetrics config - so custom container build is gonna be needed - which is why I would rather not go this route.
    https://docs.datadoghq.com/integrations/openmetrics/

    I would rather push metrics to datadogstatsd - however this client doesn't understand openmentrics format as a source... so one way out would be to write custom "api bulder" script (openmetrics -> builder).

    so that's my feature request i supposed - kindly support openmetrics as a source.

    opened by linuxd3v 0
  • ->event call's return varies based on whether UDP mode is being used

    ->event call's return varies based on whether UDP mode is being used

    If UDP is not being used, ->event returns true or false based on success. If UDP is used, ->event returns null. This can probably be fixed by seeing if ->packets_sent == 1 after the call to ->eventUdp, as that indicates success (and yes, I know UDP is send-and-pray).

    opened by jeffdafoe 0
  • Feature/injectable transport

    Feature/injectable transport

    Fixes #115

    • Proposed code changes (minimal, interface based)
    • Test fix (I was authoring on Windows, and it was a pain, I could not run tests. It's 2-liner)
    • ~GitHub actions (until I'd fixed, I actually had a really slow feedback loop)~
    • Editor config and git attributes
    • Proposed Documentation (words are hard, forgive me if it's not perfect).
    • Update to support PHP 8.0 & 8.1 thanks to Yoast
    • Tests
    • PHP 5.6 - PHP 8.1 (circleci missing 8.1-node-browsers image 🀷 )
    • Linting, Code-Style

    The actual guard portion of this, doesn't have to be owned by this repo. In the README.md I added a section with example to bypass the magic, re-using the Ipv4Udp transport that is part of this PR, so that an example of instrumenting the control I was looking for (bypassing the magic in current constructor) is available.

    I'm not πŸ’― sure about the construct with single method interface, but felt that opening and closing the socket separately to the functionality; could make some future testing easier. I Also didn't want to open a long-lived socket (although the classes don't hint at that, the way they are used in one place enforces for-now).

    The interfaces are pretty stripped-back to deal with PHP 5.6 minimum. Not sure where DataDog is going with that, but I think users would get a lot of benefit rolling up to only 7.4 & 8+ in a future release.

    Why interfaces

    Short answer. I Hate the array approach. It's too open a design, and leads to choices where spooky [mis]configuration can happen. While this one interface won't change the entire codebase, it nudges in a direction a lot of PHP coders are going.

    I'm not sure that adding strict_mode to counteract the magic will make this code any more readable or be the right way to counteract the magic cascade. For an upstream vendor to us this, implement the interface, I believe is a far more intentional choice, that leaves the majority of users happy where they are now. Internal getenv may be a feature for people who have not had silent misconfiguration lead to confusing bugs.

    Another reason for an interface based approach is that I think a test implementation that allows spy test-double would be a nice thing that this allows. Instead of using curl spy test class and the socket spy test class, which are namespace coordination dependent.

    Lastly, This interface approach would enable any coder:

    • To perform unit or integration level tests without needing to setup DataDog agent at all.
    • Could also help if falling-back in cases where perhaps the transport might use a PSR Logger, and send using Datadog API key as a log message.
    opened by Lewiscowles1986 2
  • Constructor guards

    Constructor guards

    Due to a mis-configuration at work, our agent host was in some cases not being set.

    This led to (luckily dev/qa time) discovering a PHP warning is thrown at runtime if the class is constructed with an incorrect value.

    Like a lot of 12-factor apps, we get our value from ENV, which in our case resulted in no errors and a booting app. But warnings silently output.

    I think the constructor of DogStatsTimer should throw if the host configuration is not a valid hostname or IP address. In our case it was false πŸ˜‚

    I Know people SHOULD NOT have warnings output in QA or production environments. But separate to that issue, I would be interesting in contributing this change if the authors are amenable.

    opened by Lewiscowles1986 3
Releases(1.5.5)
  • 1.5.5(May 20, 2022)

  • 1.5.4(Mar 30, 2022)

    • Fix regression preventing string values in set(). thanks to @colinodell
    • Fix boolean tag values, thanks to @roippi
    • Adding suppport for a metric prefix, thanks to @scott-shields-github
    • Add CircleCI status badge, thanks to @peter279k
    Source code(tar.gz)
    Source code(zip)
  • 1.5.3(Feb 17, 2021)

  • 1.5.2(Oct 12, 2020)

  • 1.5.1(Sep 2, 2020)

  • 1.5.0(May 6, 2020)

  • 1.4.0(Apr 16, 2019)

    • Add the DD_AGENT_HOST and DD_DOGSTATSD_PORT environment variables support for client configuration
    • Get the dd.internal.entity_id tag from the DD_ENTITY_ID environment variable
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Oct 17, 2018)

  • 1.2.0(Sep 27, 2018)

  • 1.1.0(Sep 27, 2018)

  • 1.0.2(Jun 21, 2018)

  • 1.0.1(Jun 21, 2018)

  • 1.0.0(Dec 26, 2017)

  • 0.5.0(Dec 20, 2017)

    0.5.0 / 2017-12-20

    • Update code to respect PSR1 and PSR2
    • Add support for 'aggregation_key' and 'source_type_name' for UDP events
    • Escape line break in event text over UDP
    • Align tags behaviour across all function and between UDP and TCP
    • Handle tags with no values
    • Allow single tags to be passed as strings and format multiple tags correctly (thanks to @krixon)
    Source code(tar.gz)
    Source code(zip)
  • 0.4.0(May 24, 2016)

    0.4.0 / 2016-05-24

    • Add the ability to send events via both TCP and UDP (default is UDP)
    • Update file_get_contents to cURL for better TCP event submission reliability
    • Add ability to configure SSL verification for cURL request (default validates host/peer)
    • Random code cleaning (spellchecking, fixing invalid typing, etc.)
    • Thanks to [@folkhack][], [@jmparks-ebates][], [@Amaroq1][] and [@baweinbe][] for this ([#41][]).
    Source code(tar.gz)
    Source code(zip)
  • 0.3.0(Jul 27, 2015)

    0.3.0 / 2015-07-27

    • [BUGFIX] Fix report_metric bad reference to report method in BatchedDatadogstatsd class, #27
    • [BUGFIX] Reference private variables with self:: instead of static::, #24 (thanks @shadowhand)
    • [OTHER] Add a 3-clause BSD license, #4 #28
    • [OTHER] Add a Changelog #28
    • [OTHER] Add PHP 5.3 requirement to the composer, #26
    • [OTHER] Readme update to reflect last changes, #23 #25 #26 (thanks @bigthyme)
    Source code(tar.gz)
    Source code(zip)
Owner
Datadog, Inc.
Datadog, Inc.
Instrument commands/workers/custom code with datadog, newrelic, tideways, symfony, spx.

sourceability/instrumentation This library provides a simple interface to start and stop instrumenting code with APMs. Symfony commands and messenger

null 15 Jun 6, 2022
Complete Pipedrive API client for PHP

Complete Pipedrive API client for PHP Contribute by referral code / link This won't take much time. You could use my referral code or link to get up t

Israel OrtuΓ±o 155 Dec 7, 2022
A GETTR.com client library written in PHP with Laravel support.

Gettr API Clinet PHP A GETTR.com client library written in PHP with Laravel support. This library uses unofficial publicly accessible API endpoints of

null 10 Dec 13, 2022
SendCloud client for PHP

SendCloud client for PHP Installation composer require guangda/sendcloud Example $mailData = [ 'to'=>'[email protected]', 'subject'=>'test',

Guangda 3 Aug 27, 2021
Bearer client for the PHP programming language

Bearer PHP Client This is the official PHP client for interacting with Bearer.sh. Installation Install the package by running: composer require bearer

Bearer 9 Oct 31, 2022
The most widely used PHP client for RabbitMQ

php-amqplib This library is a pure PHP implementation of the AMQP 0-9-1 protocol. It's been tested against RabbitMQ. The library was used for the PHP

php-amqplib 4.2k Jan 3, 2023
kafka php client

Kafka-php δΈ­ζ–‡ζ–‡ζ‘£ Kafka-php is a pure PHP kafka client that currently supports greater than 0.8.x version of Kafka, this project v0.2.x and v0.1.x are in

Weibo Ad Platform Open Source 1.4k Jan 5, 2023
Artax is an asynchronous HTTP client for PHP based on Amp

Artax is an asynchronous HTTP client for PHP based on Amp. Its API simplifies standards-compliant HTTP resource traversal and RESTful web service consumption without obscuring the underlying protocol. The library manually implements HTTP over TCP sockets; as such it has no dependency on ext/curl.

AMPHP 21 Dec 14, 2022
Grpc go-server php-client

Grpc go-server php-client

ε‡― 1 Jan 24, 2022
Idiomatic PHP client for Google Compute.

Google Compute for PHP Idiomatic PHP client for Google Compute. API Documentation NOTE: This repository is part of Google Cloud PHP. Any support reque

Google APIs 3 Jun 13, 2022
An unofficial EdgeDB PHP client.

Unofficial EdgeDB HTTP PHP client Requirements PHP >= 8.0 (with fileinfo and mbstring) An EdgeDB server instance (tested with 1.0+9ecadfc) Quickstart

T3d 7 Aug 18, 2022
A standalone Amazon S3 (REST) client for PHP 5/CURL

Amazon S3 PHP Class Usage OO method (e,g; $s3->getObject(...)): $s3 = new S3($awsAccessKey, $awsSecretKey); Statically (e,g; S3::getObject(...)): S3::

Donovan SchΓΆnknecht 1k Jan 3, 2023
A PHP implementation of RabbitMQ Client for webman plugin.

workbunny/webman-rabbitmq ?? A PHP implementation of RabbitMQ Client for webman plugin. ?? A PHP implementation of RabbitMQ Client for webman plugin εΈΈ

workbunny 15 Dec 15, 2022
A PHP MySQL database client class to simplify database access

This lightweight database class is written with PHP and uses the MySQLi extension, it uses prepared statements to properly secure your queries, no need to worry about SQL injection attacks.

Khader Handal 50 Jul 30, 2022
Idiomatic PHP client for Cloud Firestore.

Cloud Firestore for PHP Idiomatic PHP client for Cloud Firestore. API documentation NOTE: This repository is part of Google Cloud PHP. Any support req

Google APIs 151 Dec 10, 2022
A PHP API client for ConvertKit

ConvertKit PHP API Client Introduction This is an API Client for the ConvertKit mailing list service for PHP versions 7.4 and up There are several cli

null 0 Aug 29, 2022
PHP client library for Coveralls API.

php-coveralls PHP client library for Coveralls. Prerequisites PHP 5.5+ for 2.x or 5.3+ for 1.x On GitHub Building on Travis CI, CircleCI, Jenkins or C

null 514 Dec 25, 2022
Idiomatic PHP client for Memorystore for Memcached.

Memorystore for Memcached for PHP Idiomatic PHP client for Memorystore for Memcached. API documentation NOTE: This repository is part of Google Cloud

Google APIs 1 Mar 20, 2022
Enterprise isEven API Client

zonuexe\isEvenApi This package is a modern, high performance, high modularity and strongly static typed enterprise quality API Client of isEven API fo

USAMI Kenta 3 Aug 26, 2021