Ruby Auto-Instrumentation

If your app is written in Ruby, you can get started quickly with Cloud Observability. Download the Auto-Installer, then configure it to communicate with your Cloud Observability Microsatellites. When you deploy your app, all supported libraries will begin sending trace data to Cloud Observability.

These Auto-Installers are forked from Datadog’s contribution of their tracers to the OpenTelemetry project. You can find the original Datadog docs here.

Supported Versions

Supported Ruby Interpreters

TypeDocumentationVersionSupport typeGem version support
MRIhttps://www.ruby-lang.org/2.6FullLatest
  2.5FullLatest
  2.4FullLatest
  2.3FullLatest
  2.2FullLatest
  2.1FullLatest
  2.0FullLatest
  1.9.3Maintenance (until August 6th, 2020)< 0.27.0
  1.9.1Maintenance (until August 6th, 2020)< 0.27.0
JRubyhttp://jruby.org/9.1.5AlphaLatest

Supported Web Services:

TypeDocumentationVersionSupport type
Pumahttp://puma.io/2.16+ / 3.6+Full
Unicornhttps://bogomips.org/unicorn/4.8+ / 5.1+Full
Passengerhttps://www.phusionpassenger.com/5.0+Full

Install the Auto-Installer

Installation instructions depend on whether or not you’re instrumenting a Ruby or Rails app. Both require a configuration block that you’ll use to add instrumentation to other libraries.

Ruby Applications

  1. Install the gem:
    gem install ls-trace.
  2. Add a configuration block to your Ruby application:

    1
    2
    3
    4
    5
    
    require 'ddtrace'
    Datadog.configure do |c|
      # Activate integrations, change tracer settings, etc...
      # By default without additional configuration, nothing will be traced.
    end
    

Rails Applications

  1. Add the ls-trace gem to your Gemfile:

    1
    2
    
     source 'https://rubygems.org'
     gem 'ls-trace'
    
  2. Install the gem:
    bundle install.

  3. Create a config/initializers/datadog.rb file containing:

    1
    2
    3
    4
    5
    
     require 'ddtrace'
     Datadog.configure do |c|
      # This will activate auto-instrumentation for Rails
      c.use :rails
     end
    

Set B3 Headers for Trace Propagation

Cloud Observability recommends using B3 headers for trace propagation as the default, especially on hybrid deployments, as it is the most widely supported header at this time.

1
2
3
4
Datadog.configure do |c|
  c.distributed_tracing.propagation_inject_style = [Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3]
  c.distributed_tracing.propagation_extract_style = [Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3]
end

Configure the Auto-Installer to Send Data to Cloud Observability

To send data from your system to Cloud Observability, you need to configure the Auto-Installer to:

  • Point to your Microsatellites
  • Send global tags required by Cloud Observability to ingest and display the data to you.

Configure the Auto-Installer for On-Premise or Developer Microsatellites

Configure the Auto-Installer to point to the Cloud Observability Microsatellites by setting these environment variables. Use the right values, depending on if you are using on-premise, Cloud Observability public, or Developer Mode Microsatellites

Start tabs

On-Premise Microsatellites

1
2
3
DD_AGENT_HOST=http[s]://<Satellite host>
DD_TRACE_AGENT_PORT=<Satellite port>
DD_TRACE_GLOBAL_TAGS="lightstep.service_name:<service_name>,lightstep.access_token:<access token>"

Developer Mode

1
2
3
DD_AGENT_HOST=http://localhost
DD_TRACE_AGENT_PORT=8360
DD_TRACE_GLOBAL_TAGS="lightstep.service_name:<service_name>,lightstep.access_token:developer"

End code tabs

The host and port values for on-premise Microsatellites is your pool address, found in your configuration file.

Configure the Auto-Installer for Public Microsatellites

If you’re using Cloud Observability’s Public Microsatellites, you need to run a proxy that encrypts the trace payload before it reaches Cloud Observability. Point your tracer to the Proxy instead of the Microsatellites. The proxy can be run as a side-car to your application. Cloud Observability provides a docker image to make this simple.

  1. To start the proxy with defaults, run:
    docker run -p 8126:8126 lightstep/reverse-proxy:latest

    You can see the complete list of options using the --help flag
    docker run lightstep/reverse-proxy:latest --help

    If you run the reverse proxy on localhost and port 8126 no additional configuration is needed. If you are running on a different host or port you’ll need to set the following environment variables:

    1
    2
    
     DD_AGENT_HOST=<proxy host>
     DD_TRACE_AGENT_PORT=<proxy port>
    
  2. To set Cloud Observability information on every span, set these global tags from the configure block created when you installed the Auto-Installer:

    • lightstep.service_name: The name of the service from which spans originate. This tag allows Cloud Observability to accurately report on your services, with features such as the Service diagram and the Service Directory
    • lightstep.access_token: The access token for the project the tracers report to. Cloud Observability Microsatellites need this token to accept and store span data from the tracer. Reports from clients with invalid or deactivated access tokens will be rejected on ingress.
    1
    2
    3
    4
    
    Datadog.configure do |c|
    ...
    c.tracer tags: { 'lightstep.access_token' => '<ACCESS_TOKEN>' }
    end
    

Troubleshooting

Following are issues you may have after instrumentation, and how to resolve them.

Operation Names Aren’t Human Readable

Symptom
Operation names in Cloud Observability are not clear or are very long and unhelpful.

This feature requires a Satellite upgrade to the June 2020 release.

This can happen because the auto-installer is getting the name from a parameter in Datadog that might not be appropriate for your language. You can set that parameter to different values to see if that results in better operation names.

You can use either the resource or the name parameter, or both.

Which to use (or if using the both, the order to use) depends on the language of the installer. Refer to the Datadog docs for more info.

To configure how the operation name is set, add the following parameter to your Microsatellite configuration:

1
2
3
4
5
receivers:
  datadog:
	operation_name_extractors:
  	  - resource
  	  - name

If you set both, the order of the values matters. Cloud Observability tries to extract a name from the first variable value. If one isn’t found, it looks for the second value and uses that.

Configure Libraries

The following table shows all supported libraries and frameworks. Each uses the configure block created when installing the Auto-Installer to activate and further configuration.

NameKeyVersions SupportedHow to configure
Action Viewaction_view>= 3.2Link
Active Model Serializersactive_model_serializers>= 0.9Link
Action Packaction_pack>= 3.2Link
Active Recordactive_record>= 3.2Link
Active Supportactive_support>= 3.2Link
AWSaws>= 2.0Link
Concurrent Rubyconcurrent_ruby>= 0.9Link
Dallidalli>= 2.7Link
DelayedJobdelayed_job>= 4.1Link
Elastic Searchelasticsearch>= 6.0Link
Ethonethon>= 0.11.0Link
Exconexcon>= 0.62Link
Faradayfaraday>= 0.14Link
Grapegrape>= 1.0Link
GraphQLgraphql>= 1.7.9Link
gRPCgrpc>= 1.10Link
MongoDBmongo>= 2.0Link
MySQL2mysql2>= 0.3.21Link
Net/HTTPhttp(Any supported Ruby)Link
Racecarracecar>= 0.3.5Link
Rackrack>= 1.4.7Link
Railsrails>= 3.2Link
Rakerake>= 12.0Link
Redisredis>= 3.2, < 4.0Link
Resqueresque>= 1.0, < 2.0Link
Rest Clientrest-client>= 1.8Link
Sequelsequel>= 3.41Link
Shoryukenshoryuken>= 4.0.2Link
Sidekiqsidekiq>= 3.5.4Link
Sinatrasinatra>= 1.4.5Link
Sucker Punchsucker_punch>= 2.0Link

Action View

Most of the time, Active Support is set up as part of Rails, but it can be activated separately:

1
2
3
4
5
6
require 'actionview'
require 'ddtrace'

Datadog.configure do |c|
  c.use :action_view, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for rendering instrumentation.action_view
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer
template_base_pathUsed when the template name is parsed. If you don’t store your templates in the views/ folder, you may need to change this value'views/'

Active Model Serializers

The Active Model Serializers integration traces the serialize event for version 0.9+ and the render event for version 0.10+.

1
2
3
4
5
6
7
8
9
require 'active_model_serializers'
require 'ddtrace'

Datadog.configure do |c|
  c.use :active_model_serializers, options
end

my_object = MyModel.new(name: 'my object')
ActiveModelSerializers::SerializableResource.new(test_obj).serializable_hash
KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for active_model_serializers instrumentation.'active_model_serializers'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Action Pack

Most of the time, Action Pack is set up as part of Rails, but it can be activated separately:

1
2
3
4
5
6
require 'actionpack'
require 'ddtrace'

Datadog.configure do |c|
  c.use :action_pack, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for rendering instrumentation.action_pack
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Active Record

Most of the time, Active Record is set up as part of a web framework (Rails, Sinatra…) however, it can be set up alone:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
require 'tmpdir'
require 'sqlite3'
require 'active_record'
require 'ddtrace'

Datadog.configure do |c|
  c.use :active_record, options
end

Dir::Tmpname.create(['test', '.sqlite']) do |db|
  conn = ActiveRecord::Base.establish_connection(adapter: 'sqlite3',
                                                 database: db)
  conn.connection.execute('SELECT 42') # traced!
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to the global setting, false for off.false
orm_service_nameService name used for the Ruby ORM portion of active_record instrumentation. Overrides service name for ORM spans if explicitly set, which otherwise inherit their service from their parent.'active_record'
service_nameService name used for database portion of active_record instrumentation.Name of database adapter (e.g. 'mysql2')
tracerDatadog::Tracer used to perform instrumentation. Usually, you don’t need to set this.Datadog.tracer

Configuring trace settings per database

You can configure trace settings per database connection by using the describes option:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Provide a `:describes` option with a connection key.
# Any of the following keys are acceptable and equivalent to one another.
# If a block is provided, it yields a Settings object that
# accepts any of the configuration options listed above.

Datadog.configure do |c|
  # Symbol matching your database connection in config/database.yml
  # Only available if you are using Rails with ActiveRecord.
  c.use :active_record, describes: :secondary_database, service_name: 'secondary-db'

  c.use :active_record, describes: :secondary_database do |second_db|
    second_db.service_name = 'secondary-db'
  end

  # Connection string with the following connection settings:
  # Adapter, user, host, port, database
  c.use :active_record, describes: 'mysql2://root@127.0.0.1:3306/mysql', service_name: 'secondary-db'

  # Hash with following connection settings
  # Adapter, user, host, port, database
  c.use :active_record, describes: {
      adapter:  'mysql2',
      host:     '127.0.0.1',
      port:     '3306',
      database: 'mysql',
      username: 'root'
    },
    service_name: 'secondary-db'
end

If ActiveRecord traces an event that uses a connection that matches a key defined by describes, it will use the trace settings assigned to that connection. If the connection does not match any of the described connections, it will use default settings defined by c.use :active_record instead.

Active Support

Most of the time, Active Support is set up as part of Rails, but it can be activated separately:

1
2
3
4
5
6
7
8
9
require 'activesupport'
require 'ddtrace'

Datadog.configure do |c|
  c.use :active_support, options
end

cache = ActiveSupport::Cache::MemoryStore.new
cache.read('city')

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
cache_serviceService name used for caching with active_support instrumentation.active_support-cache
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

AWS

The AWS integration will trace every interaction (e.g. API calls) with AWS services (S3, ElastiCache etc.).

1
2
3
4
5
6
7
8
9
require 'aws-sdk'
require 'ddtrace'

Datadog.configure do |c|
  c.use :aws, options
end

# Perform traced call
Aws::S3::Client.new.list_buckets

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for aws instrumentation'aws'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Concurrent Ruby

The Concurrent Ruby integration adds support for context propagation when using ::Concurrent::Future. Making sure that code traced within the Future#execute will have correct parent set.

You enable it through the configure block:

1
2
3
4
5
6
7
8
9
10
# Inside Rails initializer or equivalent
Datadog.configure do |c|
  # Patches ::Concurrent::Future to use ExecutorService that propagates context
  c.use :concurrent_ruby, options
end

# Pass context into code executed within Concurrent::Future
Datadog.tracer.trace('outer') do
  Concurrent::Future.execute { Datadog.tracer.trace('inner') { } }.wait
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
service_nameService name used for concurrent-ruby instrumentation'concurrent-ruby'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Dalli

Dalli integration will trace all calls to your memcached server:

1
2
3
4
5
6
7
8
9
10
11
require 'dalli'
require 'ddtrace'

# Configure default Dalli tracing behavior
Datadog.configure do |c|
  c.use :dalli, options
end

# Configure Dalli tracing behavior for single client
client = Dalli::Client.new('localhost:11211', options)
client.set('abc', 123)

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for dalli instrumentation'memcached'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

DelayedJob

The DelayedJob integration uses lifecycle hooks to trace the job executions.

You enable it through the configure block:

1
2
3
4
5
require 'ddtrace'

Datadog.configure do |c|
  c.use :delayed_job, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for DelayedJob instrumentation'delayed_job'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

The Elasticsearch integration will trace any call to perform_request in the Client object:

1
2
3
4
5
6
7
8
9
10
require 'elasticsearch/transport'
require 'ddtrace'

Datadog.configure do |c|
  c.use :elasticsearch, options
end

# Perform a query to ElasticSearch
client = Elasticsearch::Client.new url: 'http://127.0.0.1:9200'
response = client.perform_request 'GET', '_cluster/health'

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
quantizeHash containing options for quantization. May include :show with an Array of keys to not quantize (or :all to skip quantization), or :exclude with Array of keys to exclude entirely.{}
service_nameService name used for elasticsearch instrumentation'elasticsearch'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Ethon

The ethon integration will trace any HTTP request through Easy or Multi objects. Note that this integration also supports Typhoeus library which is based on Ethon.

1
2
3
4
5
require 'ddtrace'

Datadog.configure do |c|
  c.use :ethon, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
distributed_tracingEnables distributed tracingtrue
service_nameService name for ethon instrumentation.'ethon'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Excon

The excon integration is available through the ddtrace middleware:

1
2
3
4
5
6
7
8
9
10
require 'excon'
require 'ddtrace'

# Configure default Excon tracing behavior
Datadog.configure do |c|
  c.use :excon, options
end

connection = Excon.new('https://example.com')
connection.get

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
distributed_tracingEnables distributed tracingtrue
error_handlerA Proc that accepts a response parameter. If it evaluates to a truthy value, the trace span is marked as an error. By default only sets 5XX responses as errors.nil
service_nameService name for Excon instrumentation. When provided to middleware for a specific connection, it applies only to that connection object.'excon'
split_by_domainUses the request domain as the service name when set to true.false
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Configuring connections to use different settings

If you use multiple connections with Excon, you can give each of them different settings by configuring their constructors with middleware:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Wrap the Datadog tracing middleware around the default middleware stack
Excon.new(
  'http://example.com',
  middlewares: Datadog::Contrib::Excon::Middleware.with(options).around_default_stack
)

# Insert the middleware into a custom middleware stack.
# NOTE: Trace middleware must be inserted after ResponseParser!
Excon.new(
  'http://example.com',
  middlewares: [
    Excon::Middleware::ResponseParser,
    Datadog::Contrib::Excon::Middleware.with(options),
    Excon::Middleware::Idempotent
  ]
)

Where options is a Hash that contains any of the parameters listed in the table above.

Faraday

The faraday integration is available through the ddtrace middleware:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
require 'faraday'
require 'ddtrace'

# Configure default Faraday tracing behavior
Datadog.configure do |c|
  c.use :faraday, options
end

# Configure Faraday tracing behavior for single connection
connection = Faraday.new('https://example.com') do |builder|
  builder.use(:ddtrace, options)
  builder.adapter Faraday.default_adapter
end

connection.get('/foo')

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
distributed_tracingEnables distributed tracingtrue
error_handlerA Proc that accepts a response parameter. If it evaluates to a truthy value, the trace span is marked as an error. By default only sets 5XX responses as errors.nil
service_nameService name for Faraday instrumentation. When provided to middleware for a specific connection, it applies only to that connection object.'faraday'
split_by_domainUses the request domain as the service name when set to true.false
tracerDatadog::Tracer used to perform instrumentation. Usually, you don’t need to set this.Datadog.tracer

Grape

The Grape integration adds the instrumentation to Grape endpoints and filters. This integration can work side by side with other integrations like Rack and Rails.

To activate your integration, use the Datadog.configure method before defining your Grape application:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# api.rb
require 'grape'
require 'ddtrace'

Datadog.configure do |c|
  c.use :grape, options
end

# Then define your application
class RackTestingAPI < Grape::API
  desc 'main endpoint'
  get :success do
    'Hello world!'
  end
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.nil
enabledDefines whether Grape should be traced. Useful for temporarily disabling tracing. true or falsetrue
service_nameService name used for grape instrumentation'grape'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

GraphQL

The GraphQL integration activates instrumentation for GraphQL queries.

To activate your integration, use the Datadog.configure method:

1
2
3
4
5
6
7
# Inside Rails initializer or equivalent
Datadog.configure do |c|
  c.use :graphql, schemas: [YourSchema], options
end

# Then run a GraphQL query
YourSchema.execute(query, variables: {}, context: {}, operation_name: nil)

The use :graphql method accepts the following parameters. Additional options can be substituted in for options:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.nil
service_nameService name used for graphql instrumentation'ruby-graphql'
schemasRequired. Array of GraphQL::Schema objects which to trace. Tracing will be added to all the schemas listed, using the options provided to this configuration. If you do not provide any, then tracing will not be activated.[]
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Manually configuring GraphQL schemas

If you prefer to individually configure the tracer settings for a schema (e.g. you have multiple schemas with different service names), in the schema definition, you can add the following using the GraphQL API:

1
2
3
4
5
6
YourSchema = GraphQL::Schema.define do
  use(
    GraphQL::Tracing::DataDogTracing,
    service: 'graphql'
  )
end

Or you can modify an already defined schema:

1
2
3
4
5
6
YourSchema.define do
  use(
    GraphQL::Tracing::DataDogTracing,
    service: 'graphql'
  )
end

Do NOT use use :graphql in Datadog.configure if you choose to configure manually, as to avoid double tracing. These two means of configuring GraphQL tracing are considered mutually exclusive.

gRPC

The grpc integration adds both client and server interceptors, which run as middleware before executing the service’s remote procedure call. As gRPC applications are often distributed, the integration shares trace information between client and server.

To setup your integration, use the Datadog.configure method like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
require 'grpc'
require 'ddtrace'

Datadog.configure do |c|
  c.use :grpc, options
end

# Server side
server = GRPC::RpcServer.new
server.add_http2_port('localhost:50051', :this_port_is_insecure)
server.handle(Demo)
server.run_till_terminated

# Client side
client = Demo.rpc_stub_class.new('localhost:50051', :this_channel_is_insecure)
client.my_endpoint(DemoMessage.new(contents: 'hello!'))

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for grpc instrumentation'grpc'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Configuring clients to use different settings

In situations where you have multiple clients calling multiple distinct services, you may pass the Datadog interceptor directly, like so:

1
2
3
4
5
6
7
8
9
configured_interceptor = Datadog::Contrib::GRPC::DatadogInterceptor::Client.new do |c|
  c.service_name = "Alternate"
end

alternate_client = Demo::Echo::Service.rpc_stub_class.new(
  'localhost:50052',
  :this_channel_is_insecure,
  :interceptors => [configured_interceptor]
)

The integration will ensure that the configured_interceptor establishes a unique tracing setup for that client instance.

MongoDB

The integration traces any Command that is sent from the MongoDB Ruby Driver to a MongoDB cluster. By extension, Object Document Mappers (ODM) such as Mongoid are automatically instrumented if they use the official Ruby driver. To activate the integration, simply:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
require 'mongo'
require 'ddtrace'

Datadog.configure do |c|
  c.use :mongo, options
end

# Create a MongoDB client and use it as usual
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'artists')
collection = client[:people]
collection.insert_one({ name: 'Steve' })

# In case you want to override the global configuration for a certain client instance
Datadog.configure(client, options)

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
quantizeHash containing options for quantization. May include :show with an Array of keys to not quantize (or :all to skip quantization), or :exclude with Array of keys to exclude entirely.{ show: [:collection, :database, :operation] }
service_nameService name used for mongo instrumentation'mongodb'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

MySQL2

The MySQL2 integration traces any SQL command sent through mysql2 gem.

1
2
3
4
5
6
7
8
9
require 'mysql2'
require 'ddtrace'

Datadog.configure do |c|
  c.use :mysql2, options
end

client = Mysql2::Client.new(:host => "localhost", :username => "root")
client.query("SELECT * FROM users WHERE group='x'")

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for mysql2 instrumentation'mysql2'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Net/HTTP

The Net/HTTP integration will trace any HTTP call using the standard lib Net::HTTP module.

1
2
3
4
5
6
7
8
9
10
11
12
13
require 'net/http'
require 'ddtrace'

Datadog.configure do |c|
  c.use :http, options
end

Net::HTTP.start('127.0.0.1', 8080) do |http|
  request = Net::HTTP::Get.new '/index'
  response = http.request(request)
end

content = Net::HTTP.get(URI('http://127.0.0.1/index.html'))

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
distributed_tracingEnables distributed tracingtrue
service_nameService name used for http instrumentation'net/http'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

If you wish to configure each connection object individually, use Datadog.configure as it follows:

1
2
client = Net::HTTP.new(host, port)
Datadog.configure(client, options)

Racecar

The Racecar integration provides tracing for Racecar jobs. You can enable it through Datadog.configure:

1
2
3
4
5
require 'ddtrace'

Datadog.configure do |c|
  c.use :racecar, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for racecar instrumentation'racecar'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Rack

The Rack integration provides a middleware that traces all requests before they reach the underlying framework or application. It responds to the Rack minimal interface, providing reasonable values that can be retrieved at the Rack level.

This integration is automatically activated with web frameworks like Rails. If you’re using a plain Rack application, enable the integration it to your config.ru:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# config.ru example
require 'ddtrace'

Datadog.configure do |c|
  c.use :rack, options
end

use Datadog::Contrib::Rack::TraceMiddleware

app = proc do |env|
  [ 200, {'Content-Type' => 'text/plain'}, ['OK'] ]
end

run app

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.nil
applicationYour Rack application. Required for middleware_names.nil
distributed_tracingEnables distributed tracing so that this service trace is connected with a trace of another service if tracing headers are receivedtrue
headersHash of HTTP request or response headers to add as tags to the rack.request. Accepts request and response keys with Array values e.g. ['Last-Modified']. Adds http.request.headers.* and http.response.headers.* tags respectively.{ response: ['Content-Type', 'X-Request-ID'] }
middleware_namesEnable this if you want to use the middleware classes as the resource names for rack spans. Requires application option to use.false
quantizeHash containing options for quantization. May include :query or :fragment.{}
quantize.queryHash containing options for query portion of URL quantization. May include :show or :exclude. See options below. Option must be nested inside the quantize option.{}
quantize.query.showDefines which values should always be shown. Shows no values by default. May be an Array of strings, or :all to show all values. Option must be nested inside the query option.nil
quantize.query.excludeDefines which values should be removed entirely. Excludes nothing by default. May be an Array of strings, or :all to remove the query string entirely. Option must be nested inside the query option.nil
quantize.fragmentDefines behavior for URL fragments. Removes fragments by default. May be :show to show URL fragments. Option must be nested inside the quantize option.nil
request_queuingTrack HTTP request time spent in the queue of the frontend server. See HTTP request queuing for setup details. Set to true to enable.false
service_nameService name used for rack instrumentation'rack'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer
web_service_nameService name for frontend server request queuing spans. (e.g. 'nginx')'web-server'

Configuring URL quantization behavior

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Datadog.configure do |c|
  # Default behavior: all values are quantized, fragment is removed.
  # http://example.com/path?category_id=1&sort_by=asc#featured --> http://example.com/path?category_id&sort_by
  # http://example.com/path?categories[]=1&categories[]=2 --> http://example.com/path?categories[]

  # Show values for any query string parameter matching 'category_id' exactly
  # http://example.com/path?category_id=1&sort_by=asc#featured --> http://example.com/path?category_id=1&sort_by
  c.use :rack, quantize: { query: { show: ['category_id'] } }

  # Show all values for all query string parameters
  # http://example.com/path?category_id=1&sort_by=asc#featured --> http://example.com/path?category_id=1&sort_by=asc
  c.use :rack, quantize: { query: { show: :all } }

  # Totally exclude any query string parameter matching 'sort_by' exactly
  # http://example.com/path?category_id=1&sort_by=asc#featured --> http://example.com/path?category_id
  c.use :rack, quantize: { query: { exclude: ['sort_by'] } }

  # Remove the query string entirely
  # http://example.com/path?category_id=1&sort_by=asc#featured --> http://example.com/path
  c.use :rack, quantize: { query: { exclude: :all } }

  # Show URL fragments
  # http://example.com/path?category_id=1&sort_by=asc#featured --> http://example.com/path?category_id&sort_by#featured
  c.use :rack, quantize: { fragment: :show }
end

Rails

The Rails integration will trace requests, database calls, templates rendering, and cache read/write/delete operations. The integration makes use of the Active Support Instrumentation, listening to the Notification API so that any operation instrumented by the API is traced.

To enable the Rails instrumentation, create an initializer file in your config/initializers folder:

1
2
3
4
5
6
# config/initializers/datadog.rb
require 'ddtrace'

Datadog.configure do |c|
  c.use :rails, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to the global setting, false for off.nil
cache_serviceCache service name used when tracing cache activity'<app_name>-cache'
controller_serviceService name used when tracing a Rails action controller'<app_name>'
database_serviceDatabase service name used when tracing database activity'<app_name>-<adapter_name>'
distributed_tracingEnables distributed tracing so that this service trace is connected with a trace of another service if tracing headers are receivedtrue
exception_controllerClass or Module which identifies a custom exception controller class. Tracer provides improved error behavior when it can identify custom exception controllers. By default, without this option, it ‘guesses’ what a custom exception controller looks like. Providing this option aids this identification.nil
middlewareAdd the trace middleware to the Rails application. Set to false if you don’t want the middleware to load.true
middleware_namesEnables any short-circuited middleware requests to display the middleware name as a resource for the trace.false
service_nameService name used when tracing application requests (on the rack level)'<app_name>' (inferred from your Rails application namespace)
template_base_pathUsed when the template name is parsed. If you don’t store your templates in the views/ folder, you may need to change this value'views/'
tracerDatadog::Tracer used to perform instrumentation. Usually, you don’t need to set this.Datadog.tracer

Supported versions

Ruby VersionsSupported Rails Versions
2.03.0 - 3.2
2.13.0 - 4.2
2.2 - 2.33.0 - 5.2
2.44.2.8 - 5.2
2.54.2.8 - 6.0
2.65.0 - 6.0

Rake

You can add instrumentation around your Rake tasks by activating the rake integration. Each task and its subsequent subtasks will be traced.

To activate Rake task tracing, add the following to your Rakefile:

1
2
3
4
5
6
7
8
9
10
11
12
13
# At the top of your Rakefile:
require 'rake'
require 'ddtrace'

Datadog.configure do |c|
  c.use :rake, options
end

task :my_task do
  # Do something task work here...
end

Rake::Task['my_task'].invoke

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to the global setting, false for off.false
enabledDefines whether Rake tasks should be traced. Useful for temporarily disabling tracing. true or falsetrue
quantizeHash containing options for quantization of task arguments. See below for more details and examples.{}
service_nameService name used for rake instrumentation'rake'
tracerDatadog::Tracer used to perform instrumentation. Usually, you don’t need to set this.Datadog.tracer

Configuring task quantization behavior

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Datadog.configure do |c|
  # Given a task that accepts :one, :two, :three...
  # Invoked with 'foo', 'bar', 'baz'.

  # Default behavior: all arguments are quantized.
  # `rake.invoke.args` tag  --> ['?']
  # `rake.execute.args` tag --> { one: '?', two: '?', three: '?' }
  c.use :rake

  # Show values for any argument matching :two exactly
  # `rake.invoke.args` tag  --> ['?']
  # `rake.execute.args` tag --> { one: '?', two: 'bar', three: '?' }
  c.use :rake, quantize: { args: { show: [:two] } }

  # Show all values for all arguments.
  # `rake.invoke.args` tag  --> ['foo', 'bar', 'baz']
  # `rake.execute.args` tag --> { one: 'foo', two: 'bar', three: 'baz' }
  c.use :rake, quantize: { args: { show: :all } }

  # Totally exclude any argument matching :three exactly
  # `rake.invoke.args` tag  --> ['?']
  # `rake.execute.args` tag --> { one: '?', two: '?' }
  c.use :rake, quantize: { args: { exclude: [:three] } }

  # Remove the arguments entirely
  # `rake.invoke.args` tag  --> ['?']
  # `rake.execute.args` tag --> {}
  c.use :rake, quantize: { args: { exclude: :all } }
end

Redis

The Redis integration will trace simple calls as well as pipelines.

1
2
3
4
5
6
7
8
9
10
require 'redis'
require 'ddtrace'

Datadog.configure do |c|
  c.use :redis, options
end

# Perform Redis commands
redis = Redis.new
redis.set 'foo', 'bar'

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for redis instrumentation'redis'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

You can also set per-instance configuration as it follows:

1
2
3
4
5
6
7
8
9
10
customer_cache = Redis.new
invoice_cache = Redis.new

Datadog.configure(customer_cache, service_name: 'customer-cache')
Datadog.configure(invoice_cache, service_name: 'invoice-cache')

# Traced call will belong to `customer-cache` service
customer_cache.get(...)
# Traced call will belong to `invoice-cache` service
invoice_cache.get(...)

Resque

The Resque integration uses Resque hooks that wraps the perform method.

To add tracing to a Resque job:

1
2
3
4
5
6
7
8
9
10
11
require 'ddtrace'

class MyJob
  def self.perform(*args)
    # do_something
  end
end

Datadog.configure do |c|
  c.use :resque, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to the global setting, false for off.false
service_nameService name used for resque instrumentation'resque'
tracerDatadog::Tracer used to perform instrumentation. Usually, you don’t need to set this.Datadog.tracer
workersAn array including all worker classes you want to trace (e.g. [MyJob])[]

Rest Client

The rest-client integration is available through the ddtrace middleware:

1
2
3
4
5
6
require 'rest_client'
require 'ddtrace'

Datadog.configure do |c|
  c.use :rest_client, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
distributed_tracingEnables distributed tracingtrue
service_nameService name for rest_client instrumentation.'rest_client'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Sequel

The Sequel integration traces queries made to your database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
require 'sequel'
require 'ddtrace'

# Connect to database
database = Sequel.sqlite

# Create a table
database.create_table :articles do
  primary_key :id
  String :name
end

Datadog.configure do |c|
  c.use :sequel, options
end

# Perform a query
articles = database[:articles]
articles.all

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name for sequel instrumentationName of database adapter (e.g. 'mysql2')
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Only Ruby 2.0+ is supported.

Configuring databases to use different settings

If you use multiple databases with Sequel, you can give each of them different settings by configuring their respective Sequel::Database objects:

1
2
3
4
5
6
sqlite_database = Sequel.sqlite
postgres_database = Sequel.connect('postgres://user:password@host:port/database_name')

# Configure each database with different service names
Datadog.configure(sqlite_database, service_name: 'my-sqlite-db')
Datadog.configure(postgres_database, service_name: 'my-postgres-db')

Shoryuken

The Shoryuken integration is a server-side middleware which will trace job executions.

You can enable it through Datadog.configure:

1
2
3
4
5
require 'ddtrace'

Datadog.configure do |c|
  c.use :shoryuken, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for shoryuken instrumentation'shoryuken'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Sidekiq

The Sidekiq integration is a client-side and server-side middleware which will trace job queuing and executions respectively.

You can enable it through Datadog.configure:

1
2
3
4
5
require 'ddtrace'

Datadog.configure do |c|
  c.use :sidekiq, options
end

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
client_service_nameService name used for client-side sidekiq instrumentation'sidekiq-client'
service_nameService name used for server-side sidekiq instrumentation'sidekiq'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

Sinatra

The Sinatra integration traces requests and template rendering.

To start using the tracing client, make sure you import ddtrace and use :sinatra after either sinatra or sinatra/base, and before you define your application/routes:

1
2
3
4
5
6
7
8
9
10
require 'sinatra'
require 'ddtrace'

Datadog.configure do |c|
  c.use :sinatra, options
end

get '/' do
  'Hello world!'
end

Where options is an optional Hash that accepts the following parameters:

Sucker Punch

The sucker_punch integration traces all scheduled jobs:

1
2
3
4
5
6
7
8
require 'ddtrace'

Datadog.configure do |c|
  c.use :sucker_punch, options
end

# Execution of this job is traced
LogJob.perform_async('login')

Where options is an optional Hash that accepts the following parameters:

KeyDescriptionDefault
analytics_enabledEnable analytics for spans produced by this integration. true for on, nil to defer to global setting, false for off.false
service_nameService name used for sucker_punch instrumentation'sucker_punch'
tracerDatadog::Tracer used to perform instrumentation. Usually you don’t need to set this.Datadog.tracer

See also

Ruby Manual Instrumentation with OpenTracing

Measure your instrumentation quality

Updated Mar 3, 2020