---
title: 'Metric Submission: DogStatsD'
description: Submit custom metrics directly from your application.
breadcrumbs: 'Docs > Metrics > Custom Metrics > Metric Submission: DogStatsD'
---

# Metric Submission: DogStatsD

While StatsD accepts only metrics, DogStatsD accepts all three of the major Datadog data types: metrics, events, and service checks. This section shows typical use cases for metrics split down by metric types, and introduces sampling rates and metric tagging options specific to DogStatsD.

COUNT, GAUGE, and SET metric types are familiar to StatsD users. `TIMER` from StatsD is a sub-set of `HISTOGRAM` in DogStatsD. Additionally, you can submit HISTOGRAM and DISTRIBUTION metric types using DogStatsD.

**Note**: Depending on the submission method used, the actual metric type stored within Datadog might differ from the submission metric type. To get RATE metrics through DogStatsD, submit either a COUNT or HISTOGRAM metric. Count metric values and `<HISTOGRAM>.count` values are time-normalized deltas of the metric's value over the StatsD flush period.

## Functions{% #functions %}

After you [install DogStatsD](https://docs.datadoghq.com/extend/dogstatsd/), the following functions are available for submitting your metrics to Datadog depending on their metric type. The functions have the following shared parameters:

| Parameter        | Type            | Required | Description                                                                                                                                                                   |
| ---------------- | --------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<METRIC_NAME>`  | String          | Yes      | Name of the metric to submit.                                                                                                                                                 |
| `<METRIC_VALUE>` | Double          | Yes      | Value associated with your metric.                                                                                                                                            |
| `<SAMPLE_RATE>`  | Double          | No       | The sample rate to apply to the metric. Takes a value between `0` (everything is sampled, so nothing is sent) and `1` (no sample). See the Sample Rate section to learn more. |
| `<TAGS>`         | List of strings | No       | A list of tags to apply to the metric. See the Metrics Tagging section to learn more.                                                                                         |
| `<CARDINALITY>`  | Enum            | No       | The [cardinality](https://docs.datadoghq.com/containers/kubernetes/tag) of tags to assign to this metric.                                                                     |

### COUNT{% #count %}

{% dl %}

{% dt %}
`increment(<METRIC_NAME>, <SAMPLE_RATE>, <TAGS>, <CARDINALITY> )`
{% /dt %}

{% dd %}
Used to increment a COUNT metric. Stored as a `RATE` type in Datadog. Each value in the stored timeseries is a time-normalized delta of the metric's value over the StatsD flush period.
{% /dd %}

{% dt %}
`decrement(<METRIC_NAME>, <SAMPLE_RATE>, <TAGS>, <CARDINALITY>)`
{% /dt %}

{% dd %}
Used to decrement a COUNT metric. Stored as a `RATE` type in Datadog. Each value in the stored timeseries is a time-normalized delta of the metric's value over the StatsD flush period.
{% /dd %}

{% dt %}
`count(<METRIC_NAME>, <METRIC_VALUE>, <SAMPLE_RATE>, <TAGS>, <CARDINALITY>)`
{% /dt %}

{% dd %}
Used to increment a COUNT metric from an arbitrary `Value`. Stored as a `RATE` type in Datadog. Each value in the stored timeseries is a time-normalized delta of the metric's value over the StatsD flush period.
{% /dd %}

{% /dl %}

**Note**: `COUNT` type metrics can show a decimal value within Datadog since they are normalized over the flush interval to report per-second units.

#### Code examples{% #code-examples %}

Emit a `COUNT` metric-stored as a `RATE` metric-to Datadog. Learn more about the `COUNT` type in the [metric types](https://docs.datadoghq.com/metrics/types/?tab=count#definition) documentation.

Run the following code to submit a DogStatsD `COUNT` metric to Datadog. Remember to `flush`/`close` the client when it is no longer needed.

{% tab title="Python" %}

```python
from datadog import initialize, statsd
import time

options = {
    'statsd_host':'127.0.0.1',
    'statsd_port':8125
}

initialize(**options)

while(1):
  statsd.increment('example_metric.increment', tags=["environment:dev"])
  statsd.decrement('example_metric.decrement', tags=["environment:dev"])
  time.sleep(10)
```

**Note:** `statsd.count` is not supported in Python.
{% /tab %}

{% tab title="Ruby" %}

```ruby
require 'datadog/statsd'

statsd = Datadog::Statsd.new('localhost', 8125, tags: ['environment:dev'])

while true do
    statsd.increment('example_metric.increment')
    statsd.increment('example_metric.increment', tags: ['another:tag'])
    statsd.decrement('example_metric.decrement')
    statsd.count('example_metric.count', 2)
    sleep 10
end
```

{% /tab %}

{% tab title="Go" %}

```go
package main

import (
	"log"
	"time"

	"github.com/DataDog/datadog-go/v5/statsd"
)

func main() {
	statsd, err := statsd.New("127.0.0.1:8125")
	if err != nil {
		log.Fatal(err)
	}
	for true {

		statsd.Incr("example_metric.increment", []string{"environment:dev"}, 1)
		statsd.Decr("example_metric.decrement", []string{"environment:dev"}, 1)
		statsd.Count("example_metric.count", 2, []string{"environment:dev"}, 1)
		time.Sleep(10 * time.Second)
	}
}
```

{% /tab %}

{% tab title="Java" %}

```java
import com.timgroup.statsd.NonBlockingStatsDClientBuilder;
import com.timgroup.statsd.StatsDClient;
import java.util.Random;

public class DogStatsdClient {

    public static void main(String[] args) throws Exception {

        StatsDClient Statsd = new NonBlockingStatsDClientBuilder()
            .prefix("statsd")
            .hostname("localhost")
            .port(8125)
            .build();
        while (true) {
            Statsd.incrementCounter("example_metric.increment", new String[]{"environment:dev"});
            Statsd.decrementCounter("example_metric.decrement", new String[]{"environment:dev"});
            Statsd.count("example_metric.count", 2, new String[]{"environment:dev"});
            Thread.sleep(100000);
        }
    }
}
```

{% /tab %}

{% tab title=".NET" %}

```csharp
using StatsdClient;
using System;

public class DogStatsdClient
{
    public static void Main()
    {
        var dogstatsdConfig = new StatsdConfig
        {
            StatsdServerName = "127.0.0.1",
            StatsdPort = 8125,
        };

        using (var dogStatsdService = new DogStatsdService())
        {
            if (!dogStatsdService.Configure(dogstatsdConfig))
                throw new InvalidOperationException("Cannot initialize DogstatsD. Set optionalExceptionHandler argument in the `Configure` method for more information.");
            var random = new Random(0);

            while (true)
            {
                dogStatsdService.Increment("example_metric.increment", tags: new[] {"environment:dev"}, cardinality: Cardinality.Low);
                dogStatsdService.Decrement("example_metric.decrement", tags: new[] {"environment:dev"}, cardinality: Cardinality.High);
                dogStatsdService.Counter("example_metric.count", 2, tags: new[] {"environment:dev"});
                System.Threading.Thread.Sleep(random.Next(100000));
            }
        }
    }
}
```

{% /tab %}

{% tab title="PHP" %}

```php
<?php

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

use DataDog\DogStatsd;

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

while (TRUE) {
    $statsd->increment('example_metric.increment', 1, array('environment'=>'dev'), 'low');
    $statsd->decrement('example_metric.decrement', 1, array('environment'=>'dev'), 'high');
    sleep(10);
}
```

{% /tab %}

{% tab title="Node.js" %}

```javascript
const tracer = require('dd-trace');
tracer.init();

tracer.dogstatsd.increment('example_metric.increment', 1, { environment: 'dev' });
tracer.dogstatsd.decrement('example_metric.decrement', 1, { environment: 'dev' });
```

{% /tab %}

After running the code above, your metrics data is available to graph in Datadog:

{% image
   source="https://datadog-docs.imgix.net/images/metrics/custom_metrics/dogstatsd_metrics_submission/increment_decrement.7c0ebf5d364882429c85429554d8f273.png?auto=format"
   alt="Increment Decrement" /%}

Since the value is submitted as a `COUNT` it's stored as `RATE` in Datadog. To get raw counts within Datadog, apply a function to your series such as the [Cumulative Sum](https://docs.datadoghq.com/dashboards/functions/arithmetic/#cumulative-sum) or [Integral](https://docs.datadoghq.com/dashboards/functions/arithmetic/#integral) function:

{% image
   source="https://datadog-docs.imgix.net/images/metrics/custom_metrics/dogstatsd_metrics_submission/increment_decrement_cumsum.d5388005804db600db36983357b7f1a7.png?auto=format"
   alt="Increment Decrement with Cumsum" /%}

### GAUGE{% #gauge %}

{% dl %}

{% dt %}
`gauge(<METRIC_NAME>, <METRIC_VALUE>, <SAMPLE_RATE>, <TAGS>, <CARDINALITY>)`
{% /dt %}

{% dd %}
Stored as a `GAUGE` type in Datadog. Each value in the stored timeseries is the last gauge value submitted for the metric during the StatsD flush period.
{% /dd %}

{% /dl %}

#### Code examples{% #code-examples-1 %}

Emit a `GAUGE` metric-stored as a `GAUGE` metric-to Datadog. Learn more about the `GAUGE` type in the [metric types](https://docs.datadoghq.com/metrics/types/?tab=gauge#definition) documentation.

Run the following code to submit a DogStatsD `GAUGE` metric to Datadog. Remember to `flush`/`close` the client when it is no longer needed.

**Note:** Metrics submission calls are asynchronous. If you want to ensure metrics are submitted, call `flush` before the program exits.

{% tab title="Python" %}

```python
from datadog import initialize, statsd
import time

options = {
    'statsd_host':'127.0.0.1',
    'statsd_port':8125
}

initialize(**options)

i = 0

while(1):
  i += 1
  statsd.gauge('example_metric.gauge', i, tags=["environment:dev"], cardinality="low")
  time.sleep(10)
```

{% /tab %}

{% tab title="Ruby" %}

```ruby
require 'datadog/statsd'

statsd = Datadog::Statsd.new('localhost', 8125)

i = 0

while true do
    i += 1
    statsd.gauge('example_metric.gauge', i, tags: ['environment:dev'], cardinality: 'low')
    sleep 10
end
```

{% /tab %}

{% tab title="Go" %}

```go
package main

import (
	"log"
	"time"

	"github.com/DataDog/datadog-go/v5/statsd"
)

func main() {
	statsd, err := statsd.New("127.0.0.1:8125")
	if err != nil {
		log.Fatal(err)
	}
	var i float64
	for true {
		i += 1
		statsd.Gauge("example_metric.gauge", i, []string{"environment:dev"}, 1, CardinalityHigh)
		time.Sleep(10 * time.Second)
	}
}
```

{% /tab %}

{% tab title="Java" %}

```java
import com.timgroup.statsd.NonBlockingStatsDClientBuilder;
import com.timgroup.statsd.StatsDClient;
import java.util.Random;

public class DogStatsdClient {

    public static void main(String[] args) throws Exception {

        StatsDClient Statsd = new NonBlockingStatsDClientBuilder()
            .prefix("statsd").
            .hostname("localhost")
            .port(8125)
            .build();
        for (int i = 0; true; i++) {
            Statsd.recordGaugeValue("example_metric.gauge", i, new String[]{"environment:dev"});
            Thread.sleep(10000);
        }
    }
}
```

{% /tab %}

{% tab title=".NET" %}

```csharp
using StatsdClient;
using System;

public class DogStatsdClient
{
    public static void Main()
    {
        var dogstatsdConfig = new StatsdConfig
        {
            StatsdServerName = "127.0.0.1",
            StatsdPort = 8125,
        };

        using (var dogStatsdService = new DogStatsdService())
        {
            if (!dogStatsdService.Configure(dogstatsdConfig))
                throw new InvalidOperationException("Cannot initialize DogstatsD. Set optionalExceptionHandler argument in the `Configure` method for more information.");
            var random = new Random(0);

            for (int i = 0; true; i++)
            {
                dogStatsdService.Gauge("example_metric.gauge", i, tags: new[] {"environment:dev"}, cardinality: Cardinality.High);
                System.Threading.Thread.Sleep(100000);
            }
        }
    }
}
```

{% /tab %}

{% tab title="PHP" %}

```php
<?php

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

use DataDog\DogStatsd;

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

$i = 0;
while (TRUE) {
    $i++;
    $statsd->gauge('example_metric.gauge', $i, array('environment'=>'dev'), 'low');
    sleep(10);
}
```

{% /tab %}

{% tab title="Node.js" %}

```javascript
const tracer = require('dd-trace');
tracer.init();

let i = 0;
while(true) {
  i++;
  tracer.dogstatsd.gauge('example_metric.gauge', i, { environment: 'dev' });
}
```

{% /tab %}

After running the code above, your metric data is available to graph in Datadog:

{% image
   source="https://datadog-docs.imgix.net/images/metrics/custom_metrics/dogstatsd_metrics_submission/gauge.b434e5f1bee65274bd4f694b8f1c4cb4.png?auto=format"
   alt="Gauge" /%}

### SET{% #set %}

{% dl %}

{% dt %}
`set(<METRIC_NAME>, <METRIC_VALUE>, <SAMPLE_RATE>, <TAGS>, <CARDINALITY>)`
{% /dt %}

{% dd %}
Stored as a `GAUGE` type in Datadog. Each value in the stored timeseries is the count of unique values submitted to StatsD for a metric over the flush period.
{% /dd %}

{% /dl %}

#### Code examples{% #code-examples-2 %}

Emit a `SET` metric-stored as a `GAUGE` metric-to Datadog.

Run the following code to submit a DogStatsD `SET` metric to Datadog. Remember to `flush`/`close` the client when it is no longer needed.

{% tab title="Python" %}

```python
from datadog import initialize, statsd
import time
import random

options = {
    'statsd_host':'127.0.0.1',
    'statsd_port':8125
}

initialize(**options)
i = 0
while(1):
  i += 1
  statsd.set('example_metric.set', i, tags=["environment:dev"])
  time.sleep(random.randint(0, 10))
```

{% /tab %}

{% tab title="Ruby" %}

```ruby
require 'datadog/statsd'

statsd = Datadog::Statsd.new('localhost', 8125)

i = 0
while true do
    i += 1
    statsd.set('example_metric.gauge', i, tags: ['environment:dev'])
    sleep rand 10
end
```

{% /tab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"log"
	"math/rand"
	"time"

	"github.com/DataDog/datadog-go/v5/statsd"
)

func main() {
	statsd, err := statsd.New("127.0.0.1:8125")
	if err != nil {
		log.Fatal(err)
	}
	var i float64
	for true {
		i += 1
		statsd.Set("example_metric.set", fmt.Sprintf("%f", i), []string{"environment:dev"}, 1)
		time.Sleep(time.Duration(rand.Intn(10)) * time.Second)
	}
}
```

{% /tab %}

{% tab title="Java" %}

```java
import com.timgroup.statsd.NonBlockingStatsDClientBuilder;
import com.timgroup.statsd.StatsDClient;
import java.util.Random;

public class DogStatsdClient {

    public static void main(String[] args) throws Exception {

        StatsDClient Statsd = new NonBlockingStatsDClientBuilder()
            .prefix("statsd").
            .hostname("localhost")
            .port(8125)
            .build();
        for (int i = 0; true; i++) {
            Statsd.recordSetValue("example_metric.set", i, new String[]{"environment:dev"});
            Thread.sleep(random.NextInt(10000));
        }
    }
}
```

{% /tab %}

{% tab title=".NET" %}

```csharp
using StatsdClient;
using System;

public class DogStatsdClient
{
    public static void Main()
    {
        var dogstatsdConfig = new StatsdConfig
        {
            StatsdServerName = "127.0.0.1",
            StatsdPort = 8125,
        };

        using (var dogStatsdService = new DogStatsdService())
        {
            if (!dogStatsdService.Configure(dogstatsdConfig))
                throw new InvalidOperationException("Cannot initialize DogstatsD. Set optionalExceptionHandler argument in the `Configure` method for more information.");
            var random = new Random(0);

            for (int i = 0; true; i++)
            {
                dogStatsdService.Set("example_metric.set", i, tags: new[] {"environment:dev"});
                System.Threading.Thread.Sleep(random.Next(100000));
            }
        }
    }
}
```

{% /tab %}

{% tab title="PHP" %}

```php
<?php

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

use DataDog\DogStatsd;

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

$i = 0;

while (TRUE) {
    $i++;
    $statsd->set('example_metric.set', $i, 1, array('environment'=>'dev'), 'low');
    sleep(rand(0, 10));
}
```

{% /tab %}

After running the code above, your metrics data is available to graph in Datadog:

{% image
   source="https://datadog-docs.imgix.net/images/metrics/custom_metrics/dogstatsd_metrics_submission/set.62e44368af8f538e464ebf16de768ad0.png?auto=format"
   alt="Set" /%}

### HISTOGRAM{% #histogram %}

{% dl %}

{% dt %}
`histogram(<METRIC_NAME>, <METRIC_VALUE>, <SAMPLE_RATE>, <TAGS>, <CARDINALITY>)`
{% /dt %}

{% dd %}
Since multiple metrics are submitted, metric types stored (`GAUGE`, `RATE`) depend on the metric. See the [HISTOGRAM metric type](https://docs.datadoghq.com/metrics/types/?tab=histogram#definition) documentation to learn more.
{% /dd %}

{% /dl %}

#### Configuration{% #configuration %}

- Configure the aggregation to send to Datadog with the `histogram_aggregates` parameter in your [datadog.yaml configuration file](https://docs.datadoghq.com/agent/configuration/agent-configuration-files/#agent-main-configuration-file). By default, only `max`, `median`, `avg`, and `count` aggregations are sent.
- Configure the percentile aggregation to send to Datadog with the `histogram_percentiles` parameter in your [datadog.yaml configuration file](https://docs.datadoghq.com/agent/configuration/agent-configuration-files/#agent-main-configuration-file). By default, only `95pc` percentile is sent.

#### Code examples{% #code-examples-3 %}

The `HISTOGRAM` metric type is specific to DogStatsD. Emit a `HISTOGRAM` metric—stored as a `GAUGE` and `RATE` metric—to Datadog. Learn more about the `HISTOGRAM` type in the [metric types](https://docs.datadoghq.com/metrics/types/?tab=histogram#definition) documentation.

Run the following code to submit a DogStatsD `HISTOGRAM` metric to Datadog. Remember to `flush`/`close` the client when it is no longer needed.

{% tab title="Python" %}

```python
from datadog import initialize, statsd
import time
import random

options = {
    'statsd_host':'127.0.0.1',
    'statsd_port':8125
}

initialize(**options)

while(1):
  statsd.histogram('example_metric.histogram', random.randint(0, 20), tags=["environment:dev"])
  time.sleep(2)
```

{% /tab %}

{% tab title="Ruby" %}

```ruby
require 'datadog/statsd'

statsd = Datadog::Statsd.new('localhost', 8125)

while true do
    statsd.histogram('example_metric.histogram', rand 20, tags: ['environment:dev'])
    sleep 2
end
```

{% /tab %}

{% tab title="Go" %}

```go
package main

import (
	"log"
	"math/rand"
	"time"

	"github.com/DataDog/datadog-go/v5/statsd"
)

func main() {
	statsd, err := statsd.New("127.0.0.1:8125")
	if err != nil {
		log.Fatal(err)
	}

	for true {
		statsd.Histogram("example_metric.histogram", float64(rand.Intn(20)), []string{"environment:dev"}, 1)
		time.Sleep(2 * time.Second)
	}
}
```

{% /tab %}

{% tab title="Java" %}

```java
import com.timgroup.statsd.NonBlockingStatsDClientBuilder;
import com.timgroup.statsd.StatsDClient;
import java.util.Random;

public class DogStatsdClient {

    public static void main(String[] args) throws Exception {

        StatsDClient Statsd = new NonBlockingStatsDClientBuilder()
            .prefix("statsd").
            .hostname("localhost")
            .port(8125)
            .build();
        while (true) {
            Statsd.recordHistogramValue("example_metric.histogram", new Random().nextInt(20), new String[]{"environment:dev"});
            Thread.sleep(2000);
        }
    }
}
```

{% /tab %}

{% tab title=".NET" %}

```csharp
using StatsdClient;
using System;

public class DogStatsdClient
{
    public static void Main()
    {
        var dogstatsdConfig = new StatsdConfig
        {
            StatsdServerName = "127.0.0.1",
            StatsdPort = 8125,
        };

        using (var dogStatsdService = new DogStatsdService())
        {
            if (!dogStatsdService.Configure(dogstatsdConfig))
                throw new InvalidOperationException("Cannot initialize DogstatsD. Set optionalExceptionHandler argument in the `Configure` method for more information.");
            var random = new Random(0);

            while (true)
            {
                dogStatsdService.Histogram("example_metric.histogram", random.Next(20), tags: new[] {"environment:dev"}, Cardinality: Cardinality.High);
                System.Threading.Thread.Sleep(2000);
            }
        }
    }
}
```

{% /tab %}

{% tab title="PHP" %}

```php
<?php

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

use DataDog\DogStatsd;

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

while (TRUE) {
    $statsd->histogram('example_metric.histogram', rand(0, 20), 1, array('environment'=>'dev'), 'low');
    sleep(2);
}
```

{% /tab %}

The above instrumentation produces the following metrics:

| Metric                                  | Description                             |
| --------------------------------------- | --------------------------------------- |
| `example_metric.histogram.count`        | Number of times this metric was sampled |
| `example_metric.histogram.avg`          | Average of the sampled values           |
| `example_metric.histogram.median`       | Median sampled value                    |
| `example_metric.histogram.max`          | Maximum sampled value                   |
| `example_metric.histogram.95percentile` | 95th percentile sampled value           |

After running the code above, your metrics data is available to graph in Datadog:

{% image
   source="https://datadog-docs.imgix.net/images/metrics/custom_metrics/dogstatsd_metrics_submission/histogram.e9eda7db9deafde4720b0a22393c697f.png?auto=format"
   alt="Histogram" /%}

#### TIMER{% #timer %}

`TIMER` metric type in DogStatsD is an implementation of `HISTOGRAM` metric type (not to be confused with timers in the standard StatsD). It measures timing data only: for example, the amount of time a section of code takes to execute.

{% dl %}

{% dt %}
`timed(<METRIC_NAME>, <METRIC_VALUE>, <SAMPLE_RATE>, <TAGS>, <CARDINALITY>)`
{% /dt %}

{% dd %}
Since multiple metrics are submitted, metric types stored (`GAUGE`, `RATE`) depend on the metric. See the [HISTOGRAM metric type](https://docs.datadoghq.com/metrics/types/?tab=histogram#definition) documentation to learn more.
{% /dd %}

{% /dl %}

##### Configuration{% #configuration-1 %}

For a `TIMER`, the `HISTOGRAM` configuration rules apply.

##### Code examples{% #code-examples-4 %}

Emit a `TIMER` metric—stored as a `GAUGE` and `RATE` metric—to Datadog. Learn more about the `HISTOGRAM` type in the [metric types](https://docs.datadoghq.com/metrics/types/?tab=histogram#definition) documentation. Remember to `flush`/`close` the client when it is no longer needed.

{% tab title="Python" %}
In Python, timers are created with a decorator.

```python
from datadog import initialize, statsd
import time
import random

options = {
    'statsd_host':'127.0.0.1',
    'statsd_port':8125
}

initialize(**options)

@statsd.timed('example_metric.timer', tags=["environment:dev,function:my_function"])
def my_function():
  time.sleep(random.randint(0, 10))

while(1):
  my_function()
```

or with a context manager:

```python
from datadog import statsd
import time
import random

def my_function():

  # First some stuff you don't want to time
  sleep(1)

  # Now start the timer
  with statsd.timed('example_metric.timer', tags=["environment:dev"]):
    # do something to be measured
    sleep(random.randint(0, 10))

while(1):
  my_function()
```

{% /tab %}

{% tab title="PHP" %}

```php
<?php

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

use DataDog\DogStatsd;

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

function runfunction() {
    sleep(rand(0, 20));
}

while (TRUE) {
  $start_time = microtime(TRUE);
  runfunction();
  $statsd->microtiming('example_metric.timer', microtime(TRUE) - $start_time);
}
```

{% /tab %}

As DogStatsD receives the timer metric data, it calculates the statistical distribution of render times and sends the following metrics to Datadog:

| Metric                              | Description                             |
| ----------------------------------- | --------------------------------------- |
| `example_metric.timer.count`        | Number of times this metric was sampled |
| `example_metric.timer.avg`          | Average time of the sampled values      |
| `example_metric.timer.median`       | Median sampled value                    |
| `example_metric.timer.max`          | Maximum sampled value                   |
| `example_metric.timer.95percentile` | 95th percentile sampled value           |

DogStatsD treats `TIMER` as a `HISTOGRAM` metric. Whether you use the `TIMER` or `HISTOGRAM` metric type, you are sending the same data to Datadog. After running the code above, your metrics data is available to graph in Datadog:

{% image
   source="https://datadog-docs.imgix.net/images/metrics/custom_metrics/dogstatsd_metrics_submission/timer.0e38d350a03747f960f1ee0c9f08f2f5.png?auto=format"
   alt="Timer" /%}

### DISTRIBUTION{% #distribution %}

{% dl %}

{% dt %}
`distribution(<METRIC_NAME>, <METRIC_VALUE>, <TAGS>, <CARDINALITY>)`
{% /dt %}

{% dd %}
Stored as a `DISTRIBUTION` type in Datadog. See the dedicated [Distribution documentation](https://docs.datadoghq.com/metrics/distributions/) to learn more.
{% /dd %}

{% /dl %}

#### Code examples{% #code-examples-5 %}

The `DISTRIBUTION` metric type is specific to DogStatsD. Emit a `DISTRIBUTION` metric-stored as a `DISTRIBUTION` metric-to Datadog. Learn more about the `DISTRIBUTION` type in the [metric types](https://docs.datadoghq.com/metrics/types/?tab=distribution#definition) documentation.

Run the following code to submit a DogStatsD `DISTRIBUTION` metric to Datadog. Remember to `flush`/`close` the client when it is no longer needed.

{% tab title="Python" %}

```python
from datadog import initialize, statsd
import time
import random

options = {
    'statsd_host':'127.0.0.1',
    'statsd_port':8125
}

initialize(**options)

while(1):
  statsd.distribution('example_metric.distribution', random.randint(0, 20), tags=["environment:dev"])
  time.sleep(2)
```

{% /tab %}

{% tab title="Ruby" %}

```ruby
require 'datadog/statsd'

statsd = Datadog::Statsd.new('localhost', 8125)

while true do
    statsd.distribution('example_metric.distribution', rand 20, tags: ['environment:dev'])
    sleep 2
end
```

{% /tab %}

{% tab title="Go" %}

```go
package main

import (
	"log"
	"math/rand"
	"time"

	"github.com/DataDog/datadog-go/v5/statsd"
)

func main() {
	statsd, err := statsd.New("127.0.0.1:8125")
	if err != nil {
		log.Fatal(err)
	}

	for true {
		statsd.Distribution("example_metric.distribution", float64(rand.Intn(20)), []string{"environment:dev"}, 1)
		time.Sleep(2 * time.Second)
	}
}
```

{% /tab %}

{% tab title="Java" %}

```java
import com.timgroup.statsd.NonBlockingStatsDClientBuilder;
import com.timgroup.statsd.StatsDClient;
import java.util.Random;

public class DogStatsdClient {

    public static void main(String[] args) throws Exception {

        StatsDClient Statsd = new NonBlockingStatsDClientBuilder()
            .prefix("statsd").
            .hostname("localhost")
            .port(8125)
            .build();
        while (true) {
            Statsd.recordDistributionValue("example_metric.distribution", new Random().nextInt(20), new String[]{"environment:dev"});
            Thread.sleep(2000);
        }
    }
}
```

{% /tab %}

{% tab title=".NET" %}

```csharp
using StatsdClient;
using System;

public class DogStatsdClient
{
    public static void Main()
    {
        var dogstatsdConfig = new StatsdConfig
        {
            StatsdServerName = "127.0.0.1",
            StatsdPort = 8125,
        };

        using (var dogStatsdService = new DogStatsdService())
        {
            if (!dogStatsdService.Configure(dogstatsdConfig))
                throw new InvalidOperationException("Cannot initialize DogstatsD. Set optionalExceptionHandler argument in the `Configure` method for more information.");
            var random = new Random(0);

            while (true)
            {
                dogStatsdService.Distribution("example_metric.distribution", random.Next(20), tags: new[] {"environment:dev"});
                System.Threading.Thread.Sleep(2000);
            }
        }
    }
}
```

{% /tab %}

{% tab title="PHP" %}

```php
<?php

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

use DataDog\DogStatsd;

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

while (TRUE) {
    $statsd->distribution('example_metric.distribution', rand(0, 20), 1, array('environment'=>'dev'), 'high');
    sleep(2);
}
```

{% /tab %}

{% tab title="Node.js" %}

```javascript
const tracer = require('dd-trace');
tracer.init();

while(true) {
  tracer.dogstatsd.distribution('example_metric.distribution', Math.random() * 20, { environment: 'dev' });
  await new Promise(r => setTimeout(r, 2000));
}
```

{% /tab %}

The above instrumentation calculates the `sum`, `count`, `average`, `minimum`, `maximum`, `50th percentile` (median), `75th percentile`, `90th percentile`, `95th percentile` and `99th percentile`. Distributions can be used to measure the distribution of *any* type of value, such as the size of uploaded files, or classroom test scores.

## Metric submission options{% #metric-submission-options %}

### Sample rates{% #sample-rates %}

Since the overhead of sending UDP packets can be too great for some performance intensive code paths, DogStatsD clients support sampling (only sending metrics a percentage of the time). It's useful if you sample many metrics, and your DogStatsD client is not on the same host as the DogStatsD server. The trade off: you decrease traffic but lose some precision and granularity.

A sample rate of `1` sends metrics 100% of the time, while a sample rate of `0` sends metrics 0% of the time.

Before sending a metric to Datadog, DogStatsD uses the `<SAMPLE_RATE>` to correct the metric value depending on the metric type (to estimate the value without sampling):

| Metric Type    | Sample rate correction                                                                                                                                                         |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `COUNT`        | Values received are multiplied by (`1/<SAMPLE_RATE>`). It's reasonable to assume that for one datapoint received, `1/<SAMPLE_RATE>` were actually sampled with the same value. |
| `GAUGE`        | No correction. The value received is kept as is.                                                                                                                               |
| `SET`          | No correction. The value received is kept as is.                                                                                                                               |
| `HISTOGRAM`    | The `histogram.count` statistic is a COUNT metric, and receives the correction outlined above. Other statistics are gauge metrics and aren't "corrected".                      |
| `DISTRIBUTION` | Values received are counted (`1/<SAMPLE_RATE>`) times. It's reasonable to assume that for one datapoint received, `1/<SAMPLE_RATE>` were actually sampled with the same value. |

#### Code examples{% #code-examples-6 %}

The following code only sends points half of the time:

{% tab title="Python" %}

```python
statsd.increment('loop.count', sample_rate=0.5)
```

{% /tab %}

{% tab title="Ruby" %}

```ruby
statsd.increment('loop.count', :sample_rate => 0.5)
```

{% /tab %}

{% tab title="Go" %}

```go
statsd.Incr("example_metric.increment", []string{}, 0.5)
```

{% /tab %}

{% tab title="Java" %}

```java
Statsd.incrementCounter("example_metric.increment", sampleRate=0.5);
```

{% /tab %}

{% tab title=".NET" %}

```csharp
dogStatsdService.Increment("example_metric.increment", sampleRate: 0.5);
```

{% /tab %}

{% tab title="PHP" %}

```php
<? php
$statsd->increment('example_metric.increment', $sampleRate->0.5);
```

{% /tab %}

### Metric tagging{% #metric-tagging %}

Add tags to any metric you send to DogStatsD with the `tags` parameter.

#### Code examples{% #code-examples-7 %}

The following code only adds the `environment:dev` and `account:local` tags to the `example_metric.increment` metric:

{% tab title="Python" %}

```python
statsd.increment('example_metric.increment', tags=["environment:dev","account:local"])
```

{% /tab %}

{% tab title="Ruby" %}

```ruby
statsd.increment('example_metric.increment', tags: ['environment:dev','account:local'])
```

{% /tab %}

{% tab title="Go" %}

```go
statsd.Incr("example_metric.increment", []string{"environment:dev","account:local"}, 1)
```

{% /tab %}

{% tab title="Java" %}

```java
Statsd.incrementCounter("example_metric.increment", new String[]{"environment:dev","account:local"});
```

{% /tab %}

{% tab title=".NET" %}

```csharp
dogStatsdService.Increment("example_metric.increment", tags: new[] {"environment:dev","account:local"})
```

{% /tab %}

{% tab title="PHP" %}
The `tags` argument can be a string:

```php
$statsd->increment('example_metric.increment', 1.0, "environment:dev,account:local");
```

or an array:

```php
<?php
$statsd->increment('example_metric.increment', 1.0, array('environment' => 'dev', 'account' => 'local'));
```

{% /tab %}

{% tab title="Node.js" %}

```javascript
tracer.dogstatsd.increment('example_metric.increment', 1, { environment: 'dev', account: 'local' });
```

{% /tab %}

#### Host tag{% #host-tag %}

The host tag is assigned automatically by the Datadog Agent aggregating the metrics. Metrics submitted with a host tag not matching the Agent hostname lose reference to the original host. The submitted host tag overrides any hostname collected by or configured in the Agent.

## Further reading{% #further-reading %}

- [Introduction to DogStatsD](https://docs.datadoghq.com/extend/dogstatsd/)
- [Datadog Metric Types](https://docs.datadoghq.com/metrics/types/)
