GithubHelp home page GithubHelp logo

dogstatsd-csharp-client's Introduction

DogStatsD for C#

Build status

A C# DogStatsD client. DogStatsD is an extension of the StatsD metric server for Datadog.

See CHANGELOG for details.

Installation

Grab the package from NuGet, or get the source from here and build it yourself.

Platforms

DogStatsD-CSharp-Client supports the following platforms:

  • .NET Standard 1.3 or greater
  • .NET Core 1.0 or greater
  • .NET Framework 4.5.1 or greater

Configuration

At start of your application, configure an instance of DogStatsdService class like this:

// The code is located under the StatsdClient namespace
using StatsdClient;

// ...

var dogstatsdConfig = new StatsdConfig
{
    StatsdServerName = "127.0.0.1",
    StatsdPort = 8125,
};

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

See the full list of available DogStatsD Client instantiation parameters.

Supported environment variables:

  • The client can use the DD_AGENT_HOST and (optionally) the DD_DOGSTATSD_PORT environment variables to build the target address if the StatsdServerName and/or StatsdPort parameters are empty.
  • If the DD_ENTITY_ID enviroment variable is found, its value will be injected as a global dd.internal.entity_id tag. This tag will be used by the Datadog Agent to insert container tags to the metrics.

Where StatsdServerName is the hostname or address of the StatsD server, StatsdPort is the optional DogStatsD port number, and Prefix is an optional string that is prepended to all metrics.

Usage via the DogStatsdService class or the static DogStatsd class.

For usage of DogStatsD metrics, events, and Service Checks the Agent must be running and available.

Here is an example to submit different kinds of metrics with DogStatsdService.

// The code is located under the StatsdClient namespace
using StatsdClient;

// ...

var dogstatsdConfig = new StatsdConfig
{
    StatsdServerName = "127.0.0.1",
    StatsdPort = 8125,
};

using (var service = new DogStatsdService())
{
    if (!service.Configure(dogstatsdConfig))
        throw new InvalidOperationException("Cannot initialize DogstatsD. Set optionalExceptionHandler argument in the `Configure` method for more information.");
                    
    service.Increment("example_metric.increment", tags: new[] { "environment:dev" });
    service.Decrement("example_metric.decrement", tags: new[] { "environment:dev" });
    service.Counter("example_metric.count", 2, tags: new[] { "environment:dev" });

    var random = new Random(0);

    for (int i = 0; i < 10; i++)
    {
        service.Gauge("example_metric.gauge", i, tags: new[] { "environment:dev" });
        service.Set("example_metric.set", i, tags: new[] { "environment:dev" });
        service.Histogram("example_metric.histogram", random.Next(20), tags: new[] { "environment:dev" });
        System.Threading.Thread.Sleep(random.Next(10000));
    }
}  

Here is another example to submit different kinds of metrics with DogStatsd.

// The code is located under the StatsdClient namespace
using StatsdClient;

// ...

var dogstatsdConfig = new StatsdConfig
{
    StatsdServerName = "127.0.0.1",
    StatsdPort = 8125,
};

if (!DogStatsd.Configure(dogstatsdConfig))
    throw new InvalidOperationException("Cannot initialize DogstatsD. Set optionalExceptionHandler argument in the `Configure` method for more information.");
DogStatsd.Increment("example_metric.increment", tags: new[] { "environment:dev" });
DogStatsd.Decrement("example_metric.decrement", tags: new[] { "environment:dev" });
DogStatsd.Counter("example_metric.count", 2, tags: new[] { "environment:dev" });

var random = new Random(0);

for (int i = 0; i < 10; i++)
{
    DogStatsd.Gauge("example_metric.gauge", i, tags: new[] { "environment:dev" });
    DogStatsd.Set("example_metric.set", i, tags: new[] { "environment:dev" });
    DogStatsd.Histogram("example_metric.histogram", random.Next(20), tags: new[] { "environment:dev" });
    System.Threading.Thread.Sleep(random.Next(10000));
}
  
DogStatsd.Dispose(); // Flush all metrics not yet sent

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 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.

Usage via the Statsd class

Statsd has been removed in v6.0.0 because it is not thread safe and not efficient. Use DogStatsdService or DogStatsd instead:

  • Methods from DogStatsdService and DogStatsd do not block when called except for Flush and Dispose.
  • DogStatsdService and DogStatsd batch automatically several metrics in one datagram.

Unix domain socket support

The version 6 (and above) of the Agent accepts packets through a Unix Socket datagram connection. Details about the advantages of using UDS over UDP are available in the Datadog DogStatsD Unix Socket documentation.

You can use unix domain socket protocol by setting StatsdServerName property to unix://YOUR_FULL_PATH, for example unix:///tmp/dsd.socket. Note that there are three / as the path of the socket is /tmp/dsd.socket.

var dogstatsdConfig = new StatsdConfig
{    
    StatsdServerName = "unix:///tmp/dsd.socket"  
};

The property StatsdMaxUnixDomainSocketPacketSize of StatsdConfig defines the maximum size of the payload. Values higher than 8196 bytes are ignored.

The feature is not supported on Windows platform. Windows has support for unix domain socket, but not for unix domain socket of type Dgram (SocketType.Dgram).

On MacOS Mojave, setting more than 2048 bytes for StatsdMaxUnixDomainSocketPacketSize is experimental.

Client side aggregation

By default, metrics for basic types (gauges, counts, sets) are aggregated before they are sent. For example, instead of sending 3 times my_metric:10|c|#tag1:value, DogStatsD client sends my_metric:30|c|#tag1:value once. For more technical details about how client-side aggregation works see #134.

Enabling client-side aggregation has the benefit of reducing the network usage and also reducing the load for DogStatsD server (Datadog Agent).

When an application sends a lot of different contexts but each context appears with a very low frequency, enabling client-side aggregation may take more memory and more CPU. A context identifies a metric name, a tag set and a metric type. The metric datadog.dogstatsd.client.aggregated_context reported by DogStatsD C# client counts the number of contexts in memory used for client-side aggregation. There is also the metric datadog.dogstatsd.client.metrics_by_type that represents the number of metrics submitted by the client before aggregation.

Configuration

The aggregation window is two seconds by default and can be changed using the FlushInterval. Note that the aggregation window on the Agent side is 10 seconds for DogStatsD metrics. For example, setting an aggregation window of 3s in the client produces a spike in your dashboard every 30s for counts metrics (as the third 10s bucket on the Agent is received 4 samples from the client).

To disable client-side aggregation set ClientSideAggregation to null.

Testing

  1. Restore packages
dotnet restore
  1. Run the tests
dotnet test tests/StatsdClient.Tests/

Feedback

To suggest a feature, report a bug, or general discussion, create a new issue in the Github repo.

Credits

dogstatsd-csharp-client is forked from Goncalo Pereira's original StatsD client.

Copyright (c) 2012 Goncalo Pereira and all contributors. See MIT-LICENCE.md for further details.

Thanks to Goncalo Pereira, Anthony Steele, Darrell Mozingo, Antony Denyer, and Tim Skauge for their contributions to the original client.

dogstatsd-csharp-client's People

Contributors

alistair avatar clamoriniere avatar darrellmozingo avatar elijahandrews avatar ganeshkumarsv avatar gdryke avatar gh123man avatar goncalopereira avatar irabinovitch avatar jbarciauskas avatar jdasilva-olo avatar josh- avatar jpasichnyk avatar kevingosse avatar l0k0ms avatar lucaspimentel avatar nathanrobb avatar nrjohnstone avatar ogaca-dd avatar remeh avatar remh avatar shreyamsh avatar skolima avatar tim-skauge avatar torreysorensen-spok avatar truthbk avatar windsnow98 avatar wjdavis5 avatar yannmh avatar yori-s avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dogstatsd-csharp-client's Issues

Strong-naming assembly

Have you considered strong-naming the StatsdClient.dll assembly? I'm trying to use your NuGet package with my own strongly-named assembly, which doesn't work.

(When compiling my project I get an error:
"Assembly generation failed -- Referenced assembly 'StatsdClient' does not have a strong name")

.NET Framework 4.6.1 dependency System.Net.NameResolution

Hello there!

I was wondering why .NET Framework 4.5.1 doesn't have the dependency System.Net.NameResolution and 4.6.1 has. So, I forked the project and tried to build 4.6.1 without the dependency from System.Net.NameResolution and it worked.
Is there any reason why there is this dependency?

Best regards,

Missing UDS (Unix Domain Socket) support

Hey, I've been developing a C# application using .NET Core on MacOS, and am deploying to a Kubernetes cluster on EC2 Linux. I want to emit custom metrics to my cluster's Datadog agents. The Datadog documentation for containerized applications suggests that UDS is the simplest way to configure a Kubernetes application for custom metrics: https://docs.datadoghq.com/agent/kubernetes/dogstatsd/

Emitting over UDP is a more complex configuration in containerized environment, and also means the application needs to include origin tagging information in each packet. These docs talk more generally of the dogstatsd UDS feature and why it exists. https://docs.datadoghq.com/developers/dogstatsd/unix_socket/

I know that Unix Domain Sockets sound like a weird request of a C# project, but with the proliferation of dotnetcore there are more and more people running .NET applications in Linux ecosystems and containerized environments.

Here's an example of another DD library's changes for UDS: https://github.com/DataDog/dogstatsd-ruby/pull/61/files

Output on console

With versions 2.2.0 every time is there a call to:

DogStatsd.Counter

in console I see these strings:

Command length 25
MaxUDP size 512

Flush method not part of interface IDogStatsd

The PR #144 added Flush to DogStatsdService but it is not present in the interface IDogStatsd that that service implements. So code that uses the interface instead of the concrete implementation cannot flush without also disposing the service.

Metrics stop updating after k8s agent is redeployed.

I am running a .net core client using dogstatsd-csharp-client to send custom metrics to a V6 datadog agent . The client is running in a kubernetes pod talking to the agent which is running on the same node. When everything is deployed the metrics are transmitted and received correctly. However, if I redeploy the datadog agent the metrics are no longer received. I can however run the following command from the pod the client is running on and still get custom metrics.

  • echo -n "custom_metric:50|g|#shell" >/dev/udp/172.21.97.95/8125

If I redeploy the client afterwards everything starts to communicate correctly once again.

.NET Core support

Hi

Following the release of .NET Core, it would be great to extend support for this / netstandard.

Blocking calls within dogstatsd client

We have recently profiled the performance of our application and we can see that the dogstatsd package is taking a surprising amount of CPU time. When we looked deeper, we found that the dogstatsd is reserving an entire thread to poll a ConcurrentQueue for metrics. This tread polls the queue, and then waits. This wait time is wasted CPU time, and for high performance applications is a waste of resources. The main culprit is:

namespace StatsdClient.Worker
{
    internal class Waiter : IWaiter
    {
        public void Wait(TimeSpan duration)
        {
            Task.Delay(duration).Wait();
        }
    }
}

but Task.Wait() is called in multiple places within the package. By moving to async await, or by using some sort of event based timer, you release that thread back to the thread pool so it can be used by the main application. Can we get some thoughts on if/how this can be solved? We are very interested in seeing this blocking wait removed

NuGet Package has NUnit dependency

The 2.0.0 NuGet package has a dependency on NUnit although it's only necessary to run the tests.

It can be worked around for the moment by running:

Install-Package Dogstatsd-CSharp-Client -IgnoreDependencies

DogStatsd class methods not visible in .net MVC classes

Hi datadoghq.com support team,

Installed Package DogStatsD-CSharp-Client 3.3.0.0 from nuget.org in .net web MVC application using .NET framework 4.5.1 and VS 2015
methods of DogStatsd class not visible in intelisence in .NET user defined classes . Methods not accessible.

Dispose does not allow to re-configure the library

I am expecting that calling the static method DogStatsd.Dispose() would invalidate the last configuration sent to the static DogStatsd.Configure, but it still returns the exception InvalidOperationException with the message Configuration for DogStatsdService already performed when called a second time.

Expected behaviour

Scenario 1

Does not throw an exception:

DogStatsd.Configure(configuration1);
DogStatsd.Dispose();
DogStatsd.Configure(configuration2);

Scenario 2

Throws an exception:

DogStatsd.Configure(configuration1);
DogStatsd.Configure(configuration2);

Actual behaviour

Throws an exception:

DogStatsd.Configure(configuration1);
DogStatsd.Dispose();
DogStatsd.Configure(configuration2);

DogStatsD starts increasing metrics indefinitely if it fails to flush metrics

Recently we faced a problem with our DataDog metrics. We have several metrics we are sending from our ASP.Net Core app, and most of them are simple counter metrics. We call the IDogStatsd.Increment method. 99.999% of all metrics are OK and sent to DataDog without issues. But sometimes we generate a metric that doesn't fit the buffer, and then we get an InvalidOperationException.
See code here

throw new InvalidOperationException($"The metric size exceeds the buffer capacity {Capacity}: {serializedMetric.ToString()}");

It's not a problem by itself, and we've already fixed the issue on our side. But other counters using IDogStatsd.Increment go nuts when it happens (all counter metrics are constantly increasing).
Screen Shot 2022-06-20 at 12 47 15 pm
Looks like DogStatsD keeps trying to flush the metrics but keeps crashing on the broken one. The only way to solve this problem is to kill the service. I guess the broken metric should be excluded rather than retried every time. Looks like the problem started in version 7.0.0. Also, as the flush process runs asynchronously, we cannot handle this exception, making it hard to investigate the issue. DogStatsD doesn't return or write the exception to logs.

When DogStatsdService is not disposed in an AppDomain, the AppDomain cannot be unloaded

This was originally observed in a CI environment using DotCover to run NUnit tests where it led to hung builds.

After a lot of digging, I was able to pin this down to a what strongly appears to be a bug that occurs when the code is running in .NET Framework 64-bit release builds using RyuJIT (which is the default 64-bit JIT). I was able to observe in the debugger that a ThreadAbortException, which in this case was triggered by AppDomain.Unload, would be thrown repeatedly without exciting the while loop inside of AsynchronousWorker. Eventually the unload times out and will throw a CannotUnloadAppDomainException. I was very fortunate to find this blog post which details the exact same scenario.

Thanks to @WramblinWreck, who started the debugging and narrowed it down to the DogStatsdService.

Afaict, the issue manifests from the addition of this catch, which should not change behavior. I assume the JIT optimizes something incorrectly which causes the ThreadAbortException to not be re-thrown at the end of the catch as it should be.

The workaround is to catch and rethrow the ThreadAbortException manually and I've got a PR incoming shortly.

Events through API endpoint

When sending events, I get many errors like this in the Dogstatsd log in the Datadog agent:

2015-12-07 10:57:09 Coordinated Universal Time | ERROR | dogstatsd(dogstatsd.pyc:311) | Error receiving datagram
Traceback (most recent call last):
  File "dogstatsd.pyc", line 298, in start
error: [Errno 10040] A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself

I've been talking about this with Datadog support and they recommend using the Event HTTP endpoint instead: http://docs.datadoghq.com/api/#events . Can we get that implemented in this library?

Thanks

AspNet Core Integration Tests Fail "OneTimeSetUp: System.InvalidOperationException : Configuration for DogStatsdService already performed"

In AspNet Core when writing integration tests to call my Api, we get the exception

OneTimeSetUp: System.InvalidOperationException : Configuration for DogStatsdService already performed"

when our Startup class calls DogStatsd.Configure(statsDConfiguration);

The reason is because for aspnet core integration tests we are going to create the web server for each test, i.e. Startup.cs will run multiple times.

    // repeated for each test
    using (var server = new TestServer(new WebHostBuilder().UseStartup<Startup>()))
    using (var client = server.CreateClient())
    {
        var response = await client.GetAsync("/api/hello");
    }

I found this article describing the scenario and how they solved it for a different third party dependency: https://blog.markvincze.com/tear-down-your-asp-net-core-api-between-integration-tests/

I think we might need a way to unregister/dispose from the static instance of DogStatsd so that _config kept in DogStatsdService can be reset to null.

As a workaround, I just keep a static flag in my Startup logic to stop from calling DogStatsd.Configure(...) more than once. But this is a less than ideal solution in my opinion.

Does this support the REST API?

I use GCP cloud run so we can't run a local agent.

We could write metrics directly to datadog with the REST API, but we'd prefer to use the statsd protocol.

Does this library support writing statsd metrics to datadog with the REST API instead of the agent?

Feature Request: Lazily tagged timers

We'd like to use the niceties of StartTimer(), but we're writing a DelegatingHandler to wrap web requests. We plan to tag the timer and related metric w/ the route pattern, but that isn't available until after the request completes.

var routeTemplate = request.GetRouteData().Route.RouteTemplate;
// routeTemplate is blank, since this gets resolved later in the pipeline so this doesn't work
using (DogStatsd.StartTimer("request.server"), new[] {$"route:{routeTemplate}")
{
    var response = await base.SendAsync(request, cancellationToken);
    return response;
}

If

  1. The MetricsTimer was returned as a MetricsTimer from the StartTimer
    and
  2. MetricsTimer exposed an AddTag or something we could add the route tag before the return in the using block.

If there's a better way to do it, I'd be happy to close. Thanks a lot!

Should use non-static instance of Statsd instead, so static initialization is not required

DogStatsd.Timer(_name, _stopWatch.ElapsedMilliseconds(), _sampleRate, _tags);

If you create a new instance of DogStatsdService providing it with configuration data for your environment, but do not statically initialize DogStatsd, and then run a StartTimer("some.metric.name") no data will make it to DataDog. However if you call a .Increment("some.other.metric.name") on that same instance it will work. IMO, MetricsTimer constructor should accept the Statsd instance it will be used for, and that instance should be used instead of the static when reporting the timer.

Array Index out of range exception (Metrics.StartTimer())

There seems to be a very rare index out of range exception when using the Metrics.StartTimer(). Here's what I got out of it:

System.IndexOutOfRangeException: Array index is out of range.
at System.Random.Sample () [0x00000] in :0
at System.Random.NextDouble () [0x00000] in :0
at StatsdClient.RandomGenerator.ShouldSend (Double sampleRate) [0x00000] in :0
at StatsdClient.Statsd.Send[Timing,Int32](System.String name, Int32 value, Double sampleRate, System.String[] tags) [0x00000] in :0
at StatsdClient.Metrics.Timer[Int32](System.String statName, Int32 value, Double sampleRate, System.String[] tags) [0x00000] in :0
at StatsdClient.MetricsTimer.Dispose () [0x00000] in :0

I'm running Mono on Linux.

Cannot Flush without Disposing

I need to be able to flush my metrics without disposing.

I am using Dogstatsd by calling Dogstatsd.Configure() at app startup and then calling the various metric functions during execution.

My particular use-case is such that I need to flush periodically because the app may or may not terminate at certain points and I will loose metrics that were not flushed. Currently the only way I see to flush metrics is by calling Dogstatsd.Dispose() but if I dispose, I obviously can't continue using Dogstatsd and I am unable to add a hook to Dispose when it actually terminates.

Is there a way to flush without disposing that I am not seeing?

DogStatsdService Best Practices for Optimization

Hello,

I would like to know if there are any problems with creating a new instance of DogStatsdService and dispose it for every metric update. For example I have a method like this:

        public static void IncrementSuccessCounter()
        {
            using (var dogStatsdService = new DogStatsdService())
            {
                dogStatsdService.Configure(dogstatsdConfig);
                dogStatsdService.Increment(DatadogStatsdCounters.SUCCESS, tags: new[] { "service: " + Utilities.GetAppSetting("DD_SERVICE_NAME") });
            }
        }

Is there a better way of doing this?

Use this client with Azure AppService Webjob

Hi there,

Does anyone know if we can use this client with Azure AppService Webjob to submit custom metrics via DDStatsd? We tried to use it for web jobs and unlike in App Service, which just works, we saw an error saying Parameter name: config.StatsdServerName and DD_AGENT_HOST environment variable not set. Upon further investigation, it appears the Datadog Azure App Service is using named pipe for the client SDK to connect to the DogStatsd agent. But not sure if how to configure the client in an App Service web job.

Pooled arrays for tags?

Hello,

All documentation instanciate a new string array for tags every time we need to increment a metrics counter. Example:

service.Increment("example_metric.increment", tags: new[] { "environment:dev" });

I'd like to limit the array allocations in order to limit stress to the GC. When possible, I set tags as static readonly, for example:

private static readonly string[] _myTags = ["environment:dev"];

public void DoSomething() {
  service.Increment("example_metric.increment", tags: _myTags);
}

It's often not possible to use a static array of tags. Is it possible to recycle an array of tags to multiple calls to service.Increment with different values of the tags, for example as follows ?

// Re-use an array of tags, but change the value of one of the tags
public void DoSomething() {
  var myTags = ["environment:dev", "myTag:A"];
  service.Increment("example_metric.increment", tags: _myTags);

  // Change the value of the second tag
  myTags[1] = "myTag:B";
  service.Increment("example_metric.increment", tags: _myTags);
}

// Borrow the tags array from a pool
public void DoSomethingElse() {
  var myTags = ArrayPool<string>.Shared.Rent(2);
  
  myTags[0] = "environment:dev";
  myTags[1] = "myTag:A";
  service.Increment("example_metric.increment", tags: _myTags);

  ArrayPool<string>.Shared.Return(myTags);
}

I'm afraid the tags arrays are processed (serialized) asynchronously, which mean we must ensure the array is not modified after a call to service.Increment.

Dogstatsd client doesn't send metrics as histogram

Hi,

I'm using the version below
<PackageReference Include="DogStatsD-CSharp-Client" Version="3.3.0" />

and the metrics sent as Histogram via the library are stored as a summary in StatsD.

Is that the default behaviour? how can I change that?

Code used:

StatsdClient.DogStatsd.Histogram("request_tracking", elapsed, tags: new[] { $"path:{path}" });

Add Sending of Events

It would be great if this client could send events via dogstatsd as well as metrics.

How to check if connectivity to Datadog is good

Is there a way to check connectivity to Datadog is good based on the configuration settings?

Having something like this would be useful to include in things like health checks so I can determine if things like custom metrics are being sent. Beyond the Configure call, if say the DD port is wrong, I do not know if connectivity is broken.

I see PR #183 has been added recently. This goes some of the way to being able to identify problems.

However, does anything exist today other than manually wiring up a UDP connection and testing out of band of the client? Not withstanding UDP being connectionless.

Unhandled Exception on Telemetry.Flush() when Statsd server is not up

When Telemetry is enabled and the Statsd server is not running, the following Exception is unhandled:

Unhandled exception. System.Net.Sockets.SocketException (111): Connection refused
   at StatsdClient.StatsSender.Send(Byte[] buffer, Int32 length)
   at StatsdClient.Telemetry.SendMetric(String metricName, Int32 value)
   at StatsdClient.Telemetry.Flush()
   at StatsdClient.Telemetry.<.ctor>b__13_0(Object _)
   at System.Threading.TimerQueueTimer.<>c.<.cctor>b__23_0(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.TimerQueueTimer.CallCallback(Boolean isThreadPool)
   at System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool)
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.TimerQueue.AppDomainTimerCallback(Int32 id)

AppVeyor builds failing

It looks like your appveyor build environment is broken.

Looking at the logs for #47 and #50, you can see that it's complaining about
C:\Program Files\dotnet\sdk\1.0.1\Microsoft\VisualStudio\v14.0\DotNet\Microsoft.DotNet.Props
being missing.

Assembly is not Strong-Named

It looks like the 3.0.0 is not Strong-Named which is causing problems with my own Strong Named assembly.

Would it be possible to get these assemblies signed in future releases?

Async Support

Currently the library performs blocking IO when sending messages. Is there any plan to add async support?

Need for try/catch?

This isn't so much an issue, as a question. Although the answer isn't super clear, so maybe that's the issue :)

Is there a need to wrap usage of DogStatsd in try/catch?

To borrow from sample in readme:

// The code is located under the StatsdClient namespace
using StatsdClient;

// ...

var dogstatsdConfig = new StatsdConfig
{
    StatsdServerName = "127.0.0.1",
    StatsdPort = 8125,
};

DogStatsd.Configure(dogstatsdConfig);
// Like this?
try
{
    DogStatsd.Increment("example_metric.increment", tags: new[] { "environment:dev" });
}
catch (Exception ex)
{
}
// ...

This came up when adding this in to our application during code review. I hate adding this kind of try/catch, but the idea is this should be like logging; any failures should do so silently.

DogStatsd.Configure does not catch SocketException "No such host is known" when the agent host cannot be found in DNS

I call DogStatsd.Configure once on application start. I ran into an issue where I had configured the agent wrong and so the agent pod in my cluster was not starting and the DNS entry was not yet added for the agent. This cascaded to where my application was failing to start because it would crash because the DNS lookup was failing and the exception was bubbling up the stack and was unhandled.

Now, I could write my own logic to catch this and retry on a background thread and queue the pending metrics. But I think the internals of this library already do that for transient network issues after it connects once, so it feels most appropriate for this library to also handle the DNS lookup failure.

Here's the stack trace:

 ---> System.Net.Sockets.SocketException (11001): No such host is known.
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Dns.HostResolutionEndHelper(IAsyncResult asyncResult)
   at System.Net.Dns.EndGetHostEntry(IAsyncResult asyncResult)
   at System.Net.Dns.<>c.<GetHostEntryAsync>b__27_1(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at StatsdClient.StatsdUDP.GetIpv4Address(String name)
   at StatsdClient.StatsdBuilder.CreateUDPStatsSender(StatsdConfig config, String statsdServerName)
   at StatsdClient.StatsdBuilder.CreateStatsSender(StatsdConfig config, String statsdServerName)
   at StatsdClient.StatsdBuilder.BuildStatsData(StatsdConfig config)
   at StatsdClient.DogStatsdService.Configure(StatsdConfig config)
   at StatsdClient.DogStatsd.Configure(StatsdConfig config)

Statsd.Event.GetCommand() throws when payload is too large

Should this call throw an exception when a payload is too large? Because there's no simple way to calculate the size of the resulting payload before calling the method; there's no way to properly guard against this condition. So throwing an exception may not be the best idea here, especially for a logging library.

Perhaps it is better to simply truncate the text of the event if it's too large? I'm happy to submit a PR to address this.

throw new Exception(string.Format("Event {0} payload is too big (more than 8kB)", title));

Thanks!

DogStatsd client stops sending metrics after Datadog agent restarts

DogStatsd client version: 5.0.2
Datadog agent version: 7.21.1
Datadog helm chart version: 2.4.14

We are encountering an issue with a Kubernetes setup. Datadog agent is deployed as a Helm chart, containers using the Dogstatsd client are based on the mcr.microsoft.com/dotnet/core/aspnet:3.1 image. The containers are sending gauge metrics using the Dogstatsd client. Every time the agent restarts, metrics stop being sent. A restart of the client container is needed. No error or exception seem to indicate any problem.

This seems to be related to the PR #125 but we are using the version 5.0.2 so it could also be unrelated.

If you need more information I can get it. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.