Skip to content

Instantly share code, notes, and snippets.

@ericmustin
Last active July 1, 2021 13:02
Show Gist options
  • Save ericmustin/4eb62f73b03655a833f2ef62716d68bd to your computer and use it in GitHub Desktop.
Save ericmustin/4eb62f73b03655a833f2ef62716d68bd to your computer and use it in GitHub Desktop.
datadog opentelemetry example sampler for a Sinatra Ruby app
require 'opentelemetry/sdk'
require 'opentelemetry-instrumentation-sinatra'
require 'opentelemetry/exporter/otlp'
# Implements sampling based on a probability.
class DatadogTraceIdRatioBased < ::OpenTelemetry::SDK::Trace::Samplers::TraceIdRatioBased
def initialize(probability)
@probability = probability
super(probability)
end
# @api private
#
# See {Samplers}.
def should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:)
tracestate = ::OpenTelemetry::Trace.current_span(parent_context).context.tracestate
if sample?(trace_id)
::OpenTelemetry::SDK::Trace::Samplers::Result.new(decision: ::OpenTelemetry::SDK::Trace::Samplers::Decision::RECORD_AND_SAMPLE, attributes: {'_sample_rate' => @probability}, tracestate: tracestate)
else
::OpenTelemetry::SDK::Trace::Samplers::Result.new(decision: ::OpenTelemetry::SDK::Trace::Samplers::Decision::RECORD_ONLY, attributes: {'_sample_rate' => @probability}, tracestate: tracestate)
end
end
end
OpenTelemetry::SDK.configure do |c|
c.use 'OpenTelemetry::Instrumentation::Sinatra'
c.add_span_processor(
OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
OpenTelemetry::Exporter::OTLP::Exporter.new()
)
)
end
OpenTelemetry.tracer_provider.sampler = ::OpenTelemetry::SDK::Trace::Samplers.parent_based(root: DatadogTraceIdRatioBased.new(0.5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment