A library for working with StatsD in PHP

Related tags

Miscellaneous statsd
Overview

StatsD PHP Library

Build Status Total Downloads Latest Stable Version

A library for working with StatsD in PHP.

Install

Via Composer:

composer require league/statsd

To use the Statsd Service Provider, you must register the provider when bootstrapping your Laravel application.

Usage

Configuring

$statsd = new League\StatsD\Client();
$statsd->configure([
    'host' => '127.0.0.1',
    'port' => 8125,
    'namespace' => 'example'
]);

OR

$statsd1 = StatsD\Client::instance('server1')->configure([...]);
$statsd2 = StatsD\Client::instance('server2')->configure([...]);

The StatsD client wait for ini_get('default_socket_timeout') seconds when opening the socket by default. To reduce this timeout, add 'timeout' => to your config.

The StatsD client will throw a ConnectionException if it is unable to send data to the StatsD server. You may choose to disable these exceptions and log a PHP warning instead if you wish. To do so, include the following in your config:

    'throwConnectionExceptions' => false

If omitted, this option defaults to true.

Counters

$statsd->increment('web.pageview');
$statsd->decrement('storage.remaining');
$statsd->increment([
    'first.metric',
    'second.metric'
], 2);
$statsd->increment('web.clicks', 1, 0.5);

Gauges

$statsd->gauge('api.logged_in_users', 123456);

Sets

$userID = 23;
$statsd->set('api.unique_logins', $userID);

Timers

$statsd->timing('api.response_time', 256);
$metrics = array('api.response_time' => 256, 'api.memory' => 4096));
$statsd->timings($metrics);

Timing Blocks

$statsd->time('api.dbcall', function () {
    // this code execution will be timed and recorded in ms
});

Tags

Attention! That functionality support of tags in Datadog format!

You may configure it for all the metrics sending by the client.

$statsd->configure([
    'tags' => ['some_general_tag' => 'value']
]);

Or you may send it for a single metric.

$statsd->increment('web.clicks', 1, 1, ['host' => $_SERVER['HTTP_HOST']]);

Framework integration

Although this library will work with any PHP framework, below are a few ways to integrate it quickly with the most popular ones via included adapters.

Laravel 4.x

Find the providers key in your app/config/app.php and register the Statsd Service Provider.

    'providers' => [
        // ...
        'League\StatsD\Laravel\Provider\StatsdServiceProvider',
    ]

Find the aliases key in your app/config/app.php and add the Statsd Facade Alias.

    'aliases' => [
        // ...
        'Statsd' => 'League\StatsD\Laravel\Facade\StatsdFacade',
    ]

Laravel 5.x

If you are using Laravel >=5.5, statsd uses package discovery to automatically register the service provider and facade.

For older versions of Laravel 5, or if you disable package discovery:

Find the providers key in your config/app.php and register the Statsd Service Provider.

    'providers' => [
        // ...
        League\StatsD\Laravel5\Provider\StatsdServiceProvider::class,
    ]

Find the aliases key in your app/config/app.php and add the Statsd Facade Alias.

    'aliases' => [
        // ...
        'Statsd' => League\StatsD\Laravel5\Facade\StatsdFacade::class,
    ]

Lumen

Register the provider in your boostrap app file boostrap/app.php

Add the following line in the "Register Service Providers" section at the bottom of the file.

$app->register(\League\StatsD\Laravel5\Provider\StatsdServiceProvider::class);

Copy the config file statsd.php manually from the directory /vendor/league/statsd/config to the directory /config (you may need to create this directory).

Package Configuration

In your .env file, add the configuration:

STATSD_HOST=127.0.0.1
STATSD_PORT=8125
STATSD_NAMESPACE=

Testing

phpunit

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Bump version for stable support in packagist

    Bump version for stable support in packagist

    Can't utilize the addition of League\Statsd\Client::set() without lowering stability to dev. Please tag a new stable version of this client and release on packagist.

    opened by jakemcgraw 9
  • Allow optional disabling of connection exceptions

    Allow optional disabling of connection exceptions

    Metrics gathering on my project is a welcome bonus, but not a critical feature, so I don't want a page load to fail if it can't connect to StatsD. I also don't want to wrap every invocation with:

    try {
        // ... do statsd stuff
    } (catch ConnectionException $e) {
        // do nothing
    }
    

    I could just write a wrapper to do all that transparently, but I think "just log a warning and keep loading the page" is a common enough use case, and making the exception throwing configurable would be a helpful contribution.

    The throwConnectionExceptions configuration setting is completely optional, and it will throw exceptions by default like it does now (so there is no BC issue).

    opened by michaelmoussa 8
  • Release new semantic version

    Release new semantic version

    It's been a long time since last semantic version was released and master has some nice and useful features fixes. It would be very helpful to issue new stable release with semantic version.

    opened by vgarvardt 6
  • Call to undefined method [package]

    Call to undefined method [package]

    Hey! Just installed it on Laravel 5.1 - got this error.

    in ServiceProvider.php line 234
    at ServiceProvider->__call('package', array('league/statsd', 'statsd')) in StatsdServiceProvider.php line 23
    at StatsdServiceProvider->package('league/statsd', 'statsd') in StatsdServiceProvider.php line 23
    at StatsdServiceProvider->boot()
    at call_user_func_array(array(object(StatsdServiceProvider), 'boot'), array()) in Container.php line 507
    at Container->call(array(object(StatsdServiceProvider), 'boot')) in Application.php line 734
    at Application->bootProvider(object(StatsdServiceProvider)) in Application.php line 717
    at Application->Illuminate\Foundation\{closure}(object(StatsdServiceProvider), '20')
    at array_walk(array(object(EventServiceProvider), object(RoutingServiceProvider), object(AuthServiceProvider), object(ControllerServiceProvider), object(CookieServiceProvider), object(DatabaseServiceProvider), object(EncryptionServiceProvider), object(FilesystemServiceProvider), object(FormRequestServiceProvider), object(FoundationServiceProvider), object(PaginationServiceProvider), object(SessionServiceProvider), object(ValidationServiceProvider), object(ViewServiceProviderEx), object(AppServiceProvider), object(EventServiceProvider), object(RouteServiceProvider), object(SlackServiceProvider), object(BugsnagLaravelServiceProvider), object(ServiceProvider), object(StatsdServiceProvider), object(HashServiceProvider)), object(Closure)) in Application.php line 718
    at Application->boot() in BootProviders.php line 17
    at BootProviders->bootstrap(object(Application)) in Application.php line 203
    at Application->bootstrapWith(array('Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Illuminate\Foundation\Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders')) in Kernel.php line 222
    at Kernel->bootstrap() in Kernel.php line 117
    at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
    at Kernel->handle(object(Request)) in index.php line 54
    
    opened by lezhnev74 6
  • How to approach Laravel 5 pull request?

    How to approach Laravel 5 pull request?

    The Laravel Service Provider of this package does not work with Laravel 5. I could easily make a Pull Request to add support for Laravel 5.

    Would you all prefer a new League\StatsD**\Laravel5**\Facade\StatsdFacade or just upgrade the current Laravel facade and break compatibility with Laravel 4?

    I think a new Facade for Laravel5 would be nicer, to avoid breaking old installs.

    opened by casperbakker 6
  • Update codestyle, php version, tests, add interface

    Update codestyle, php version, tests, add interface

    This library hasn't been updated in a while. I'm not sure if that's intentional, but I've taken an attempt to modernize this library a bit. I hope an update for this library can be considered. If this is not the right approach of some changes should be left out / split in other PRs, let me know.

    I've added an interface, which would be nice to have for dependency injection and mocking in tests. Updated PHPUnit and the tests. Used the last maintained PHP version as minimum and used types where possible. Applied the PSR codestyle. Added GitHub actions configuration.

    opened by Jeroeny 5
  • Use var_export to output value without locale formatting

    Use var_export to output value without locale formatting

    Use var_export to output value without locale formatting

    For example calling setLocale(LC_ALL, 'fr-FR’); before send timing will send value with « , » instead of « . » to statsd

    opened by monptitjojo 5
  • Reuse socket connection when sending metrics

    Reuse socket connection when sending metrics

    I use your library for statsd backend in our hellofresh/stats-php library. Recently we added quite a lot of new metrics to one of our legacy monolith project to profile some bottlenecks and found that although metrics are sent via UDP we got significant performance degradation. During the investigation we found that statsd opens new socket connection for every metric being sent, that is quite expensive operation.

    I fixed the issue in our library - https://github.com/hellofresh/stats-php/pull/3 (we tested it before merging), but I think it would be useful to have this feature/fix in the base library.

    opened by vgarvardt 4
  • Fix PHPUnit test cases and configuration

    Fix PHPUnit test cases and configuration

    This PR fixes issue #46

    On PHP7 and PHPUnit 6, this repo was having trouble running the tests, mainly because PHPUnit wasn't able to find any tests because the TestCase class was extending an old version of TestCase

    Bumped the PHPUnit version and extended the correct class. Since this repo aims to support +5.6 (based on the travis configuration file) it doesn't make sense to use an old version of PHPUnit

    opened by andreskrey 4
  • Fix isset issue for php7

    Fix isset issue for php7

    This is a strange issue, so bear with me. With PHP 7.0.10-2 on Ubuntu 16.04.1, isset always returns false in the Laravel 5 provider. This doesn't happen on PHP 5.6 or PHP7 on Windows (I checked). For example, even if a host is specified, this line always evaluates to false:

    https://github.com/thephpleague/statsd/blob/master/src/Laravel5/Provider/StatsdServiceProvider.php#L50

    I used the config() global function in the Laravel 5 provider to get the config. I also just passed the config on through without checking if the parameters exist because you do that anyway in the configure function. The global config function isn't available in Laravel 4, or, obviously, Silex, so I couldn't had it there. I did, however, remove the unneeded isset checking and passed the config through like I did in the Laravel 5 provider.

    opened by ethanhann 4
  • Added a configurable timeout value for the StatsD Client

    Added a configurable timeout value for the StatsD Client

    This PR adds a configurable timeout to prevent long delays when attempting to open the socket connection. If not specified, it will default to the default_socket_timeout setting in php.ini, which is the normal behavior if no $timeout is passed to fsockopen(...).

    Note that while I've added tests for this, it's not possible to test that the $timeout value is actually being passed to fsockopen unless:

    (a) the League\StatsD\Test namespace is changed to League\StatsD, which will allow me to use the "namespace global function hack" to verify that fsockopen was called with the correct timeout, or (b) Travis needs to install the uopz Pecl module in order to "mock" the global fsockopen(...) function.

    I'd be happy to send a PR if you wish to go either route, but otherwise, this PR covers all new lines of code.

    opened by michaelmoussa 4
  • Ability to use TCP connections.

    Ability to use TCP connections.

    Rarely somebody need that feature, but in case if does, here is support for TCP connections in a pull request.

    UDP is great. It's fast, it's reliable in local connections and it even doesn't require to have server running.

    But in case your StatsD server running on other machine and your network become flooded with packages (i.e. during DDoS attack), your packets will start to get lost and your metrics won't show you the real picture. You want get real count of unique IP addresses of clients. Attendance is falling, mean/percentile looks good, but site isn't going well. That's the problem that I run into.

    Of cause it would be better to run local instances of StatsD on each server. But it's also possible to switch on TCP. You still need to set your NAT/firewall properly, cause no any authentication is used, and all your data goes in plane text thru the network.

    As far as TCP connections take resources both from client and server, I added destructor and the ability to remove static instance, to free the connection. And because of destructor, magic __clone method is also appeared with a controversial decision. As far as testing with a TCP scheme requires running TCP server and everyone have different workspace, I opted TCP tests with an STATSD_TCP_ADDRESS environment variable that should have 'host:port' of any TCP server (it could be any http-server as well, because we don't need to get any meaningful answer from the server, just an IP SYN and ACK packets). On linux systems you can use nc -lk 127.0.0.1 8125 and set STATSD_TCP_ADDRESS to '127.0.0.1:8125' (IPv6 is also supported if needed).

    Tested wit PHP 7.4, 8.0 and 8.1. Laravel integration updated. No breaking changes involved. Only minor changes:

    • New 'scheme' config that can be skipped.
    • New 'STATSD_SCHEME' environmental variable for Laravel integration, that can be skipped or set to empty (but you can't pass empty value to configure function, for now it's forbidden but can be changed if needed).
    • When you clone object it won't share the same resource anymore. So it can be called ver 2.1.

    I leave some minor phpDoc changer in separate commit, 'cause it's a controversial topic. Fell free tho throw them out or merge together.

    opened by Angel5a 0
Releases(2.0.0)
  • 2.0.0(Jan 15, 2022)

    Added

    • Added new StatsDClient interface, which Client now implements
    • Added new Exception interface, which all exceptions now implement

    Changed

    • Supported PHP versions are now 7.4, 8.0, and 8.1
    • All properties and methods now have type hints where applicable
    • gauge() now accepts both int and float values (#56)
    • ConnectionException message is now also propagated via trigger_error() (#57)
    • The following methods return the StatsDClient interface instead of Client:
      • ConfigurationException::getInstance()
      • ConnectionException::getInstance()
    • The following Client methods now return void instead of returning $this:
      • increment()
      • decrement()
      • startTiming()
      • endTiming()
      • timing()
      • timings()
      • time()
      • gauge()
      • set()
      • send()
    • Renamed Client::$instance_id to Client::$instanceId

    New Contributors

    • @Jeroeny made their first contribution in https://github.com/thephpleague/statsd/pull/59
    • @filakhtov made their first contribution in https://github.com/thephpleague/statsd/pull/57

    Full Changelog: https://github.com/thephpleague/statsd/compare/1.5.0...2.0.0

    Source code(tar.gz)
    Source code(zip)
  • 1.4.3(Jul 17, 2017)

  • 1.4.2(Feb 9, 2017)

  • 1.4.1(Feb 7, 2017)

  • 1.4.0(Apr 21, 2016)

    New Features

    • Custom timeout configurations
    • Exception handling is now configurable
    • Built-in Laravel 5 support

    Fixes

    • DNS lookup failures no longer raise exceptions
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Jun 11, 2015)

  • 1.2.0(Jun 1, 2015)

    This is a small changes with a few new features and enhancements

    • Configurable timeouts
    • SET method: Count the number of unique values passed to a key
    • PHP 5.6 Testing on Travis
    • Various test patches and improvements
    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Feb 1, 2014)

  • v1.0(Aug 27, 2013)

    This is the first fully stable version of StatsD library. This version has the following features:

    • Counters
    • Gauges
    • Timers
    • Timing Blocks
    • 100% Code Coverage
    • Silex Service Provider
    Source code(tar.gz)
    Source code(zip)
Owner
The League of Extraordinary Packages
A group of developers who have banded together to build solid, well tested PHP packages using modern coding standards.
The League of Extraordinary Packages
PHP DataDog StatsD Client

PHP DataDog StatsD Client This is an extremely simple PHP DogStatsD client. Requires PHP >= 5.6.0. See CHANGELOG.md for changes. For a Laravel-specifi

Datadog, Inc. 175 Nov 28, 2022
PHP library with basic objects and more for working with Facebook/Metas Conversions API

PHP library with basic objects and more for working with Facebook/Metas Conversions API Installation The easiest way to install this library is by ins

null 5 Dec 5, 2022
PHP library for working with Demandware XML files

PHP Demandware XML A PHP library for working with Demandware XML files. Exporting: Supports category, product, variant and assignment files and allows

Fusions PIM 3 Dec 14, 2022
Iran decoration platform is an open source Php web application where you can find your job as a freelancer working in people home in decoration positions and others.

Iran-Decoration Platform Iran decoration platform is an open source Php web application where you can find your job as a freelancer working in people

AmirHossein Mohammadi 8 Dec 14, 2022
A set of utilities for working with vk api!

vk-utils Документация на русском языке Installation composer require labile/vk-utils How to use it? Simple example use Astaroth\VkUtils\Client; $api

null 1 Jan 3, 2022
A plugin for working with popular money libraries in Pest

This package is a plugin for Pest PHP. It allows you to write tests against monetary values provided by either brick/money or moneyphp/money using the same declarative syntax you're used to with Pest's expectation syntax.

Luke Downing 19 Oct 30, 2022
A PHPStan package that supports working with Extbase

PHPStan for Extbase This package provides a couple of stubs and services to make your life easier when working with PHPStan and Extbase. Examples clas

Alexander Schnitzler 7 Dec 10, 2021
A simple package for working with money.

Money A simple package for working with money. Main features: Simple API Livewire integration Custom currency support Highly customizable formatting R

ARCHTECH 143 Nov 18, 2022
I am actively working on this - v1.3 stable-DEV

Batch-OBF-php This Obf .bat files v swag ngl only reason im posting the code is cuz i people have said im ratting them by changing the code of the .ba

INZO_Technologies 1 Jan 26, 2022
BetterWPDB - Keeps you safe and sane when working with custom tables in WordPress.

BetterWPDB - Keeps you safe and sane when working with custom tables in WordPress.

Snicco 21 Dec 15, 2022
Strings Package provide a fluent, object-oriented interface for working with multibyte string

Strings Package provide a fluent, object-oriented interface for working with multibyte string, allowing you to chain multiple string operations together using a more readable syntax compared to traditional PHP strings functions.

Glowy PHP 14 Mar 12, 2022
Tools for working with the SPDX license list and validating licenses.

composer/spdx-licenses SPDX (Software Package Data Exchange) licenses list and validation library. Originally written as part of composer/composer, no

Composer 1.4k Dec 26, 2022
A complete solution for group projects in organizations that lets you track your work in any scenario. Working in a team is a cumbersome task, ease it using our project management system.

SE-Project-Group24 What is Evolo? Evolo is Dashboard based Project Management System. A complete solution for group projects in organizations that let

Devanshi Savla 2 Oct 7, 2022
Spin up a working Statamic instance quickly & easily with Docker

Spin Up Statamic Allows you to create your own self-contained Statamic project complete site config, Antlers/Blade/Twig template files, assets, and de

nystudio107 11 Jun 2, 2023
Dobren Dragojević 6 Jun 11, 2023
Easy to use utility functions for everyday PHP projects. This is a port of the Lodash JS library to PHP

Lodash-PHP Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects. Lodash-PHP tr

Lodash PHP 474 Dec 31, 2022
PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

null 464 Dec 28, 2022
php-echarts is a php library for the echarts 5.0.

php-echarts 一款支持Apache EChart5.0+图表的php开发库 优先ThinkPHP5/6的开发及测试。 Apache EChart5.0已经最新发布,在视觉效果、动画效果和大数据展示方面已经远超之前的版本; 故不考虑EChart5.0之前版本的兼容问题;建议直接尝试5.0+

youyiio 5 Aug 15, 2022
Minimalist PHP frame for Core-Library, for Developing PHP application that gives you the full control of your application.

LazyPHP lightweight Pre-Made Frame for Core-library Install Run the below command in your terminal $ composer create-project ryzen/lazyphp my-first-pr

Ry-Zen 7 Aug 21, 2022