diff --git a/README.md b/README.md index a32f4df..b3babb4 100644 --- a/README.md +++ b/README.md @@ -56,10 +56,15 @@ DegicaDatadog::Tracing.span!("hats.process_payment") do # Process a payment. end +# Optionally specify a resource and/or tags. +resource = webhook.provider.name tags = { "merchant_uuid" => merchant.uuid, "merchant_name" => merchant.name, } +DegicaDatadog::Tracing.span!("hats.send_webhook", resource: resource, tags: tags) do + # Process a payment. +end # Add tags to the current span. DegicaDatadog::Tracing.span_tags!(**tags) diff --git a/lib/degica_datadog/tracing.rb b/lib/degica_datadog/tracing.rb index be2ae87..08825b1 100644 --- a/lib/degica_datadog/tracing.rb +++ b/lib/degica_datadog/tracing.rb @@ -41,6 +41,7 @@ def init # rubocop:disable Metrics/AbcSize,Metrics/MethodLength # Start a new span. def span!(name, **options, &block) + enrich_span_options!(options) Datadog::Tracing.trace(name, **options, &block) end @@ -84,6 +85,27 @@ def flatten_hash_for_span(hsh, key = nil) # rubocop:disable Metrics/MethodLength flattened_hash end + + # Merge in default tags and service name. + def enrich_span_options!(options) + options[:service] = Config.service + + if options[:tags] + options[:tags].merge!(default_span_tags) + else + options[:tags] = default_span_tags + end + end + + def default_span_tags + { + "env" => Config.environment, + "version" => Config.version, + "service" => Config.service, + "git.commit.sha" => Config.version, + "git.repository_url" => Config.repository_url + } + end end end end diff --git a/spec/tracing_spec.rb b/spec/tracing_spec.rb new file mode 100644 index 0000000..6fc4281 --- /dev/null +++ b/spec/tracing_spec.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +RSpec.describe DegicaDatadog::Tracing do + describe ".enrich_span_options!" do + it "adds the service name" do + options = {} + described_class.enrich_span_options!(options) + expect(options[:service]).to eq(DegicaDatadog::Config.service) + end + + it "adds the default tags if none are present" do + options = {} + described_class.enrich_span_options!(options) + expect(options[:tags]).to eq(DegicaDatadog::Tracing.default_span_tags) + end + + it "merges the default tags with the provided tags" do + options = { tags: { "foo" => "bar" } } + described_class.enrich_span_options!(options) + expect(options[:tags]).to eq(DegicaDatadog::Tracing.default_span_tags.merge("foo" => "bar")) + end + + it "overrides the provided tags with default tags" do + options = { tags: { "env" => "test" } } + described_class.enrich_span_options!(options) + expect(options[:tags]).to eq(DegicaDatadog::Tracing.default_span_tags) + end + end +end