Skip to content

Commit 0d223b0

Browse files
authored
Fix negative values being sent to Datadog (#51)
The negative sign for numbers is not taken into account when calculating the size of the encoding buffer, so writing negative values causes utf8writer to not be able to format it into the buffer. This fixes the calculation by checking if the number is negative, and using the correct value when throwing an exception.
1 parent 8bfaeca commit 0d223b0

2 files changed

Lines changed: 8 additions & 4 deletions

File tree

src/StackExchange.Metrics/Handlers/StatsdMetricHandler.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -251,9 +251,10 @@ protected override void SerializeMetric(IBufferWriter<byte> writer, in MetricRea
251251
var length = encoding.GetByteCount(reading.Name) + s_colon.Length;
252252

253253
// calculate the length needed to render the value
254-
var value = reading.Value;
254+
var value = Math.Abs(reading.Value);
255+
var valueIsNegative = reading.Value < 0;
255256
var valueIsWhole = value % 1 == 0;
256-
int valueLength = 1; // first digit
257+
int valueLength = valueIsNegative ? 2 : 1; // first digit, plus negative sign if negative
257258
if (!valueIsWhole)
258259
{
259260
valueLength += 1 + ValueDecimals; // + decimal point + decimal digits
@@ -308,7 +309,7 @@ protected override void SerializeMetric(IBufferWriter<byte> writer, in MetricRea
308309
);
309310

310311
ex.Data.Add("Name", reading.Name);
311-
ex.Data.Add("Value", valueAsLong.ToString());
312+
ex.Data.Add("Value", reading.Value.ToString());
312313
ex.Data.Add("Size", valueLength.ToString());
313314
throw ex;
314315
}
@@ -321,7 +322,7 @@ protected override void SerializeMetric(IBufferWriter<byte> writer, in MetricRea
321322
);
322323

323324
ex.Data.Add("Name", reading.Name);
324-
ex.Data.Add("Value", value.ToString("f5"));
325+
ex.Data.Add("Value", reading.Value.ToString("f5"));
325326
ex.Data.Add("Size", valueLength.ToString());
326327
throw ex;
327328
}

tests/StackExchange.Metrics.Tests/StatsdMetricHandlerTests.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ public StatsdMetricHandlerTests(ITestOutputHelper output)
3030
[InlineData(2.443d)]
3131
[InlineData(1.1234457d)]
3232
[InlineData(9.1234457d)]
33+
[InlineData(-1d)]
34+
[InlineData(-2.443d)]
35+
[InlineData(-9.1234457d)]
3336
public async Task UdpUri_Counter_ReceivesValidStatsd(double value)
3437
{
3538
var port = (ushort)_rng.Next(1024, 65535);

0 commit comments

Comments
 (0)