Skip to content

Commit

Permalink
OpenTelemetry.Extensions.AzureMonitor - Add sampleRate attribute to S…
Browse files Browse the repository at this point in the history
…amplingResult. (#623)
  • Loading branch information
rajkumar-rangaraj authored Sep 7, 2022
1 parent bc947a0 commit 1b808fd
Showing 1 changed file with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using OpenTelemetry.Internal;
using OpenTelemetry.Trace;

Expand All @@ -25,6 +26,8 @@ namespace OpenTelemetry.Extensions.AzureMonitor;
/// </summary>
public class ApplicationInsightsSampler : Sampler
{
private static readonly SamplingResult DropSamplingResult = new(false);
private readonly SamplingResult recordAndSampleSamplingResult;
private readonly float samplingRatio;

/// <summary>
Expand All @@ -38,6 +41,13 @@ public ApplicationInsightsSampler(float samplingRatio)

this.samplingRatio = samplingRatio;
this.Description = "ApplicationInsightsSampler{" + samplingRatio + "}";
var sampleRate = (int)Math.Round(samplingRatio * 100);
this.recordAndSampleSamplingResult = new SamplingResult(
SamplingDecision.RecordAndSample,
new Dictionary<string, object>
{
{ "sampleRate", sampleRate },
});
}

/// <summary>
Expand All @@ -48,8 +58,26 @@ public ApplicationInsightsSampler(float samplingRatio)
/// <returns>Returns whether or not we should sample telemetry in the form of a <see cref="SamplingResult"/> class.</returns>
public override SamplingResult ShouldSample(in SamplingParameters samplingParameters)
{
if (this.samplingRatio == 0)
{
return DropSamplingResult;
}

if (this.samplingRatio == 1)
{
return this.recordAndSampleSamplingResult;
}

double sampleScore = DJB2SampleScore(samplingParameters.TraceId.ToHexString().ToLowerInvariant());
return new SamplingResult(sampleScore < this.samplingRatio);

if (sampleScore < this.samplingRatio)
{
return this.recordAndSampleSamplingResult;
}
else
{
return DropSamplingResult;
}
}

private static double DJB2SampleScore(string traceIdHex)
Expand Down

0 comments on commit 1b808fd

Please sign in to comment.