### Start Ruby 3.4 Development Environment Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DevelopmentGuide.md Use this command to create and start a Ruby 3.4 test environment with necessary dependencies. Ensure Docker and Docker Compose are installed. ```bash # In the root directory of the project... cd ~/dd-trace-rb # Create and start a Ruby 3.4 test environment with its dependencies docker compose run --rm tracer-3.4 /bin/bash ``` -------------------------------- ### Run Setup Command Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/ruby/README.md Executes the setup script for the application within a Docker container. Use 'docker compose' if 'docker-compose' fails. ```bash docker-compose run --rm app bin/setup ``` -------------------------------- ### Install Dependencies Source: https://github.com/datadog/dd-trace-rb/blob/master/AGENTS.md Installs project dependencies using Bundler. This command should be run once per container or session. ```bash bundle install ``` -------------------------------- ### Start Rack Application with Docker Compose Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/rack/README.md Starts the webserver using Docker Compose. It binds to localhost:80 by default. ```sh docker-compose up ``` -------------------------------- ### Verify Remote Configuration Worker Start Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DynamicInstrumentationDevelopment.md Check your logs for this message to verify that the remote configuration client has started. ```text D, [timestamp] DEBUG -- datadog: new remote configuration client: products: LIVE_DEBUGGING ``` -------------------------------- ### Start Rails Application Server Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/rails-five/README.md Use docker-compose to start the Rails application. It can run the full application with a load tester or just the application itself. ```sh # Run full application + load tester # Binds to localhost:80 docker-compose up # OR # Run only the application (no load tester) # Binds to localhost:80 docker-compose run --rm -p 80:80 app "bin/run " ``` -------------------------------- ### Install Library Dependencies Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DevelopmentGuide.md Once inside the Docker container, run this command to install the Ruby gem dependencies for the trace library. ```bash # Then inside the container (e.g. `root@2a73c6d8673e:/app`)... # Install the library dependencies bundle install ``` -------------------------------- ### TypeProf Example Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/StaticTypingGuide.md Demonstrates how to use TypeProf to infer types by providing entry point calls. Ensure all relevant code paths are explored for comprehensive type coverage. ```ruby # test.rb def foo(x) p x # reveal type of x if x > 10 x.to_s else nil end end foo(42) # this call is needed otherwise there's nothing evaluated! foo(3) # make sure to explore as many codepaths as possible to get best coverage ``` ```shell $ typeprof test.rb # TypeProf 0.21.2 # Revealed types # foo.rb:3 #=> Integer # Classes class Object private def foo: (Integer x) -> String? end ``` -------------------------------- ### Execute a GraphQL Query Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Example of executing a GraphQL query. This is a basic usage pattern. ```ruby YourSchema.execute(query, variables: {}, context: {}, operation_name: nil) ``` -------------------------------- ### Configure Active Record Tracing Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Basic setup for Active Record tracing. Ensure Datadog is configured before establishing database connections. ```ruby require 'tmpdir' require 'sqlite3' require 'active_record' require 'datadog' Datadog.configure do |c| c.tracing.instrument :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 ``` -------------------------------- ### Setup OpenTelemetry Integration with Datadog Source: https://context7.com/datadog/dd-trace-rb/llms.txt Configure Datadog and OpenTelemetry SDK for unified tracing and OTLP metrics export. Ensure OpenTelemetry::SDK.configure is called AFTER Datadog.configure. ```ruby # Gemfile gem 'datadog' gem 'opentelemetry-sdk' gem 'opentelemetry-metrics-sdk', '~> 0.8' gem 'opentelemetry-exporter-otlp-metrics', '~> 0.4' # config/initializers/datadog.rb (or application boot) require 'opentelemetry/sdk' require 'datadog/opentelemetry' Datadog.configure do |c| c.service = 'my-otel-app' c.env = 'production' # Activate additional Datadog integrations alongside OTel auto-instrumentation: c.tracing.instrument :rails c.tracing.instrument :redis end # Enable OTLP metrics export via environment variables: # DD_METRICS_OTEL_ENABLED=true # OTEL_METRIC_EXPORT_INTERVAL=15000 (ms) # OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta # Initialize the OTel SDK AFTER Datadog.configure: OpenTelemetry::SDK.configure ``` -------------------------------- ### Set Up and Run Rails Server Manually Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/README.md Manually sets up and starts a Rails server for integration testing outside of Docker. Ensure to set RUBYOPT, DD_DEMO_ENV_GEM_LOCAL_DATADOG, and DATABASE_URL environment variables. ```bash cd apps/rails-seven export RUBYOPT=-I../../images/include # Use local dd-trace-rb tree export DD_DEMO_ENV_GEM_LOCAL_DATADOG=../../.. export DATABASE_URL=mysql2://user:password@localhost:3306 bundle install bundle exec rake db:create db:migrate bundle exec rails server -p 3000 ``` -------------------------------- ### Enforce Exception Message Formatting (Good Example) Source: https://github.com/datadog/dd-trace-rb/blob/master/rubocop/custom_cops/README.md This example shows the correct way to log exceptions, adhering to the convention of including both the class name and the message using `#{e.class}: #{e.message}`. ```ruby rescue => e log("#{e.class}: #{e.message}") ``` -------------------------------- ### Run Demo Application Process Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/opentelemetry/README.md Starts the demo application within a Docker container. The `` argument is optional and specifies which part of the demo to run (e.g., 'main' for OpenTelemetry traces, 'irb' for an IRB session). Defaults to DD_DEMO_ENV_PROCESS if not provided. ```sh docker-compose run --rm app bin/run ``` -------------------------------- ### Start Hanami Application with Docker Compose Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/hanami/README.md Use this command to run the full Hanami application, including a load tester, bound to localhost:80. Alternatively, run only the application by omitting the load tester. ```sh docker-compose up ``` ```sh docker-compose run --rm -p 80:80 app "bin/run " ``` -------------------------------- ### Configure Redis with Datadog for Older Versions (< 5) Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Instrument Redis connections for versions prior to 5.0 using the `redis` gem. This example shows how to configure multiple Redis instances with distinct service names. ```ruby require 'redis' require 'datadog' Datadog.configure do |c| c.tracing.instrument :redis # Enabling integration instrumentation is still required end customer_cache = Redis.new invoice_cache = Redis.new Datadog.configure_onto(customer_cache, service_name: 'customer-cache') Datadog.configure_onto(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(...) ``` -------------------------------- ### Configure Net/HTTP Tracing Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Instrument the standard Net::HTTP library to trace outgoing HTTP requests. This setup requires including the Datadog library and configuring tracing options. ```ruby require 'net/http' require 'datadog' Datadog.configure do |c| c.tracing.instrument :http, **options # optionally, specify a different service name for hostnames matching a regex c.tracing.instrument :http, describes: /user-[^.]+\.example\.com/ do |http| http.service_name = 'user.example.com' http.split_by_domain = false # Only necessary if split_by_domain is true by default end 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')) ``` -------------------------------- ### Configure PG Integration in Ruby Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Use this snippet to enable and configure the Datadog PG integration. Ensure you have the `pg` gem and `datadog` gem installed. ```ruby require 'pg' require 'datadog' Datadog.configure do |c| c.tracing.instrument :pg, **options end ``` -------------------------------- ### Configure MongoDB Tracing Per Connection Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Configure trace settings for specific MongoDB connections using the `describes` option. This allows for granular control over service names based on connection strings or regular expressions. Ensure the `mongo` gem is installed. ```ruby Datadog.configure do |c| # Network connection string c.tracing.instrument :mongo, describes: '127.0.0.1:27017', service_name: 'mongo-primary' # Network connection regular expression c.tracing.instrument :mongo, describes: /localhost.*/, service_name: 'mongo-secondary' end client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'artists') collection = client[:people] collection.insert_one({ name: 'Steve' }) # Traced call will belong to `mongo-primary` service client = Mongo::Client.new([ 'localhost:27017' ], :database => 'artists') collection = client[:people] collection.insert_one({ name: 'Steve' }) # Traced call will belong to `mongo-secondary` service ``` -------------------------------- ### Generate GRPC Proto Stubs Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DevelopmentGuide.md Run this command to regenerate Ruby code from .proto files used for testing the gRPC integration. Ensure you have Docker installed and the current directory mounted. ```bash docker run \ --platform linux/amd64 \ -v ${PWD}:/app \ -w /app \ ruby:latest \ ./spec/datadog/tracing/contrib/grpc/support/gen_proto.sh ``` -------------------------------- ### Run Basic Demo Scenarios Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/rack/README.md Executes basic demo scenarios for the Rack application, including Fibonacci calculation and a default POST request. ```sh curl -v localhost/basic/fibonacci curl -v -XPOST localhost/basic/default ``` -------------------------------- ### Enable Startup Logs Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Activate startup logs to generate a report of tracing state upon application initialization by setting `c.diagnostics.startup_logs.enabled = true`. ```ruby Datadog.configure { |c| c.diagnostics.startup_logs.enabled = true } ``` -------------------------------- ### Enable Action View Tracing Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Set up Action View tracing independently. Customize `template_base_path` if your templates are not in the default `views/` directory. ```ruby require 'actionview' require 'datadog' Datadog.configure do |c| c.tracing.instrument :action_view, **options end ``` -------------------------------- ### Start a New Trace in Ruby 1.0 Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide.md Use Datadog::Tracing.trace to start a new trace. The block receives a span and a trace object. ```ruby Datadog::Tracing.trace('my.job') do |span, trace| # Do work... # span => # # trace => # end ``` -------------------------------- ### Initialize OpenSearch Client Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Instantiate an OpenSearch client with connection details. This is a prerequisite for instrumenting OpenSearch queries. ```ruby client = OpenSearch::Client.new( host: 'https://localhost:9200', user: 'user', password: 'password', ) client.cluster.health ``` -------------------------------- ### Start Remote Configuration Worker Manually Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DynamicInstrumentationDevelopment.md Add this to your Rails initializer to enable dynamic instrumentation and start the remote configuration worker manually. This is intended for development of the datadog gem itself. ```ruby # config/initializers/datadog.rb Datadog.configure do |c| c.dynamic_instrumentation.enabled = true # This internal setting should only be used when developing the datadog gem itself and # **should not** ever be used outside of that. c.dynamic_instrumentation.internal.development = true c.remote.enabled = true # ... other configuration end # Start the RC worker if Datadog.send(:components).remote Datadog.send(:components).remote.start end ``` -------------------------------- ### Manually Finish Asynchronous Spans Source: https://context7.com/datadog/dd-trace-rb/llms.txt Use `Datadog::Tracing.trace` to start a span that you will finish manually later. This is useful for asynchronous operations where the span's end time is not known when the operation starts. ```ruby def on_event_start(name) Datadog::Tracing.trace(name) # returns SpanOperation, not finished end def on_event_finish(name, payload) span = Datadog::Tracing.active_span return unless span span.resource = payload[:query] span.set_tag('rows_affected', payload[:rows]) span.finish end ``` -------------------------------- ### Run Job Demo Scenario Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/rack/README.md Executes the job demo scenario for the Rack application via a POST request. ```sh curl -v -XPOST localhost/jobs ``` -------------------------------- ### Enforce Exception Message Formatting (Bad Examples) Source: https://github.com/datadog/dd-trace-rb/blob/master/rubocop/custom_cops/README.md These examples demonstrate incorrect ways to log exceptions, violating the convention of including both the class name and the message. The cop flags `e.class.name`, bare `#{e}`, and missing class names. ```ruby rescue => e log("#{e.class.name}: #{e.message}") # e.class.name should be e.class log("#{e.class}: #{e}") # bare #{e} should be #{e.message} log("error: #{e.message}") # missing class name log("error: #{e}") # both: bare e and missing class ``` -------------------------------- ### Access Configuration Settings (0.x vs 1.0) Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide.md Shows the difference in accessing configuration values between the older 0.x version and the new 1.0 version, highlighting the introduction of namespaces. ```ruby ### Old 0.x ### Datadog.configuration[:rails][:service_name] Datadog.configuration[:cucumber][:service_name] ### New 1.0 ### Datadog.configuration.tracing[:rails][:service_name] Datadog.configuration.ci[:cucumber][:service_name] ``` -------------------------------- ### Run Datadog Agent Docker Container Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/hanami/README.md This command starts the Datadog Agent in a Docker container, essential for monitoring Dockerized applications with Datadog. ```sh docker run --rm --name dd-agent -v /var/run/docker.sock:/var/run/docker.sock:ro -v /proc/:/host/proc/:ro -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro -e API_KEY=$DD_API_KEY datadog/docker-dd-agent:latest ``` -------------------------------- ### Show All Query String Parameters Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Configure Rack tracing to display all query string parameters. Use this when you need to see the complete query string for debugging or analysis. ```ruby c.tracing.instrument :rack, quantize: { query: { show: :all } } ``` -------------------------------- ### Distributed Tracing Propagation (HTTP) in Ruby 0.x Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide.md Example of injecting trace context into HTTP headers using the older 0.x API. ```ruby ### Old 0.x ### # Get trace continuation from active trace env = {} Datadog::HTTPPropagator.inject(Datadog.tracer.call_context, env) context = Datadog::HTTPPropagator.extract(env) # Continue a trace: implicit continuation Datadog.tracer.provider.context = context # Next trace inherits trace properties Datadog.tracer.trace('my.job') do |span| span.trace_id == context.trace_id end ``` -------------------------------- ### Run Integration Tests Manually Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/README.md Executes integration tests against a manually started Rails server. Set TEST_INTEGRATION, TEST_HOSTNAME, and TEST_PORT environment variables. ```bash cd apps/rails-seven export RUBYOPT=-I../../images/include export TEST_INTEGRATION=1 TEST_HOSTNAME=localhost TEST_PORT=3000 bundle exec rspec ``` -------------------------------- ### Distributed Tracing Propagation (HTTP) in Ruby 1.0 Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide.md Example of injecting trace state into HTTP headers using the new 1.0 API with TraceDigest. ```ruby ### New 1.0 ### # Get trace continuation from active trace trace_digest = Datadog::Tracing.active_trace.to_digest # Continue a trace: implicit continuation # Digest will be "consumed" by the next `trace` operation Datadog::Tracing.continue_trace!(trace_digest) # Next trace inherits trace properties Datadog::Tracing.trace('my.job') do |span, trace| trace.id == trace_digest.trace_id end # Second trace does NOT inherit trace properties Datadog::Tracing.trace('my.job') do |span, trace| trace.id != trace_digest.trace_id end ``` -------------------------------- ### Enable Action Pack Tracing Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Activate Action Pack tracing separately if not using the full Rails setup. The `enabled` option controls span creation. ```ruby require 'actionpack' require 'datadog' Datadog.configure do |c| c.tracing.instrument :action_pack, **options end ``` -------------------------------- ### Configure Datadog Tracer (0.x vs 1.0) Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide.md Illustrates the configuration changes for service names and instrumentation between Datadog Tracer 0.x and 1.0. In 1.0, a global `c.service` is used, and instrumentation is enabled via `c.tracing.instrument`. ```ruby ### Old 0.x ### Datadog.configure do |c| # Instrumentation that measures internal behavior c.use :rails, service_name: 'billing-api' c.use :resque, service_name: 'billing-api' c.use :sidekiq, service_name: 'billing-api' # Instrumentation that measures external services c.use :active_record, service_name: 'billing-api_mysql' # Defaults to DB type e.g. mysql c.use :http, service_name: 'billing-api_http' # Defaults to net/http c.use :redis, service_name: 'billing-api_redis' # Defaults to redis end ``` ```ruby ### New 1.0 ### Datadog.configure do |c| c.service = 'billing-api' # Instrumentation that measures internal behavior # now inherits the application's service name. c.tracing.instrument :rails c.tracing.instrument :resque c.tracing.instrument :sidekiq # Instrumentation that measures external services # defaults to adapter-specific names. You may still override # these names with the `service_name:` option. c.tracing.instrument :active_record, service_name: 'billing-api_mysql' # Defaults to DB type e.g. mysql c.tracing.instrument :http, service_name: 'billing-api_http' # Defaults to net/http c.tracing.instrument :redis, service_name: 'billing-api_redis' # Defaults to redis end ``` -------------------------------- ### Configure Service, Environment, and Tags Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Set application-level service name, environment, version, and custom tags using the `Datadog.configure` block. These can be overridden by environment variables. ```ruby Datadog.configure do |c| c.service = 'billing-api' c.env = 'test' c.tags = { 'team' => 'qa' } c.version = '1.3-alpha' end ``` -------------------------------- ### Update Specific Dependency with Custom Gemfile Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DevelopmentGuide.md Updates a specific gem ('stripe' in this example) using a custom gemfile path defined by the BUNDLE_GEMFILE environment variable. ```bash env BUNDLE_GEMFILE=/app/gemfiles/ruby_3.4_stripe_latest.gemfile bundle update stripe ``` -------------------------------- ### Handle Unsupported Environment Variables in Tests Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/AccessEnvironmentVariables.md In test environments, accessing unsupported environment variables will raise a RuntimeError. This example shows how to catch and handle this error. ```ruby # In tests, unsupported DD_/OTEL_ variables will raise errors begin DATADOG_ENV['DD_UNSUPPORTED_VAR'] rescue RuntimeError => e puts e.message # "Missing DD_UNSUPPORTED_VAR env/configuration in "supported-configurations.json" file." end ``` -------------------------------- ### Install Datadog Gem and Auto-instrument Rails/Hanami Source: https://context7.com/datadog/dd-trace-rb/llms.txt Add the datadog gem to your Gemfile with the require option for auto-instrumentation. Configure service metadata, environment, version, and tags in an initializer. ```ruby # Gemfile source 'https://rubygems.org' gem 'datadog', require: 'datadog/auto_instrument' # config/initializers/datadog.rb Datadog.configure do |c| c.service = 'my-rails-app' c.env = ENV.fetch('RAILS_ENV', 'production') c.version = ENV.fetch('APP_VERSION', nil) c.tags = { 'team' => 'backend' } end ``` -------------------------------- ### Configure Basic HTTP Client Instrumentation Source: https://context7.com/datadog/dd-trace-rb/llms.txt Enable distributed tracing for standard HTTP clients like Net::HTTP, Excon, and HTTP.rb. Requires `Datadog.configure`. ```ruby c.tracing.instrument :http, distributed_tracing: true # Net::HTTP c.tracing.instrument :excon, distributed_tracing: true c.tracing.instrument :httprb, distributed_tracing: true ``` -------------------------------- ### Configure Manual Instrumentation and Integrations in Ruby Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Set up Datadog tracing with manual instrumentation. This requires explicitly enabling the global default service name and instrumenting each integration you use. ```ruby # config/initializers/datadog.rb - you must enable each integration Datadog.configure do |c| c.service = 'my-service' c.tracing.contrib.global_default_service_name.enabled = true # Must instrument every integration you use c.tracing.instrument :redis c.tracing.instrument :faraday c.tracing.instrument :rails # ... and so on for each integration end ``` -------------------------------- ### Run Rack Application Manually Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/rack/README.md Manually starts the Rack application within a Docker container, allowing specification of the process to run. Defaults to DD_DEMO_ENV_PROCESS if no process is provided. ```sh docker-compose run --rm -p 80:80 app "bin/run " ``` -------------------------------- ### Configure Multiple Sequel Databases with Different Settings Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Configure individual Sequel::Database objects with distinct settings, such as service names, for Datadog tracing. ```ruby sqlite_database = Sequel.sqlite postgres_database = Sequel.connect('postgres://user:password@host:port/database_name') # Configure each database with different service names Datadog.configure_onto(sqlite_database, service_name: 'my-sqlite-db') Datadog.configure_onto(postgres_database, service_name: 'my-postgres-db') ``` -------------------------------- ### Configure MongoDB Tracing with Datadog Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Use this snippet to instrument a MongoDB client instance with Datadog tracing, overriding global configurations if necessary. Ensure the `mongo` gem is installed. ```ruby 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_onto(client, **options) ``` -------------------------------- ### Global Configuration with Datadog.configure Source: https://context7.com/datadog/dd-trace-rb/llms.txt The central entry point for configuring all aspects of the library, including service metadata, agent connection, tracing options, and more. Accepts a block yielding a settings object. ```APIDOC ## Datadog.configure — Global configuration block The central entry point for configuring all aspects of the library: service metadata, agent connection, tracing options, integration activation, sampling, profiling, and more. Accepts a block yielding a settings object `c`. ```ruby require 'datadog' Datadog.configure do |c| # --- Service identity (also settable via DD_SERVICE, DD_ENV, DD_VERSION, DD_TAGS) --- c.service = 'billing-api' c.env = 'production' c.version = '3.1.0' c.tags = { 'team' => 'payments', 'region' => 'us-east' } # --- Agent connection --- c.agent.host = '127.0.0.1' # DD_AGENT_HOST c.agent.port = 8126 # DD_TRACE_AGENT_PORT # OR use Unix Domain Socket: # c.agent.uds_path = '/var/run/datadog/apm.socket' # --- Tracing --- c.tracing.enabled = true # DD_TRACE_ENABLED c.tracing.log_injection = true # DD_LOGS_INJECTION c.tracing.report_hostname = false # DD_TRACE_REPORT_HOSTNAME c.tracing.sampling.default_rate = 1.0 # DD_TRACE_SAMPLE_RATE (0.0–1.0) c.tracing.sampling.rate_limit = 100 # traces/sec, DD_TRACE_RATE_LIMIT c.tracing.propagation_style_inject = ['Datadog', 'tracecontext'] c.tracing.propagation_style_extract = ['Datadog', 'tracecontext', 'b3'] # --- Diagnostics --- c.diagnostics.debug = false # DD_TRACE_DEBUG (never in prod) c.diagnostics.startup_logs.enabled = true # DD_TRACE_STARTUP_LOGS # --- Runtime metrics (requires dogstatsd-ruby ~> 5.3) --- c.runtime_metrics.enabled = true # DD_RUNTIME_METRICS_ENABLED # --- Profiling --- # Enable via DD_PROFILING_ENABLED=true or through the Datadog UI guide # --- Telemetry --- c.telemetry.enabled = true # DD_INSTRUMENTATION_TELEMETRY_ENABLED # --- Error Tracking --- c.error_tracking.handled_errors = 'user' # DD_ERROR_TRACKING_HANDLED_ERRORS c.error_tracking.handled_errors_include = ['app/controllers', 'app/models'] end ``` ``` -------------------------------- ### Configure Sidekiq Tagging (v1.x vs v2.0) Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide2.md The `tag_args` option for Sidekiq instrumentation has been removed. Use the `quantize` option instead, specifying `args: { show: :all }` to retain similar behavior. ```ruby # === with 1.x === Datadog.configure do |c| c.tracing.instrument :sidekiq, tag_args: true end # === with 2.0 === Datadog.configure do |c| c.tracing.instrument :sidekiq, quantize: { args: { show: :all } } end ``` -------------------------------- ### Excon Integration with Datadog Middleware Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Integrate Datadog tracing with the Excon library using the provided Datadog middleware. This setup enables tracing of HTTP requests made through Excon. ```ruby require 'excon' require 'datadog' ``` -------------------------------- ### Configure Basic Background Job Instrumentation Source: https://context7.com/datadog/dd-trace-rb/llms.txt Activate basic instrumentation for Active Job, Resque, Delayed Job, and Que. For Que, distributed tracing and argument tagging are enabled. Requires `Datadog.configure`. ```ruby c.tracing.instrument :active_job c.tracing.instrument :resque c.tracing.instrument :delayed_job c.tracing.instrument :que, distributed_tracing: true, tag_args: true ``` -------------------------------- ### Example of Failed CI Job Output Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/AccessEnvironmentVariables.md This JSON output illustrates a scenario where a local configuration is found but missing from the central configuration registry, causing a CI job to fail. ```json Missing properties: { "DD_TRACE_GRAPHQL_ERROR_TRACKING": [ { "version": "A", "type": "boolean", "propertyKeys": ["error_tracking"], "default": "false" } ] } The above configuration was found locally but missing from the configuration registry. ``` -------------------------------- ### Configure Hanami Integration Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Enable Hanami instrumentation by auto-instrumenting the `datadog` gem and creating an initializer file in `config/initializers`. ```ruby # config/initializers/datadog.rb Datadog.configure do |c| c.tracing.instrument :hanami, **options end ``` -------------------------------- ### Nginx Configuration for Request Queuing Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Configure Nginx to add an `X-Request-Start` header to measure time spent in the queue before the request reaches the Ruby application. ```nginx # /etc/nginx/conf.d/ruby_service.conf server { listen 8080; location / { proxy_set_header X-Request-Start "t=${msec}"; proxy_pass http://web:3000; } } ``` -------------------------------- ### Basic Trace Example in Datadog Trace Ruby 2.0 Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide2.md Demonstrates how to create a custom trace span using Datadog::Tracing.trace in version 2.0. The span ID is printed to standard output. ```ruby Datadog::Tracing.trace('my_span', type: 'custom') do |span| puts span.id span.type = "...." end ``` -------------------------------- ### Configure Datadog Tracer in Rails/Hanami Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Create an initializer file to configure the Datadog tracer. This block allows for additional configuration settings and integration activation. ```ruby Datadog.configure do |c| # Add additional configuration here. # Activate integrations, change tracer settings, etc... end ``` -------------------------------- ### Trace Database Queries Asynchronously Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Use `Datadog::Tracing.trace` without a block to manually start and finish spans for asynchronous operations like database queries. Ensure all spans are finished to avoid trace loss. ```ruby # Some instrumentation framework calls this after an event finishes... def db_query(start, finish, query) span = Datadog::Tracing.trace('database.query', start_time: start) span.resource = query span.finish(finish) end ``` -------------------------------- ### Discover Gemfiles Source: https://github.com/datadog/dd-trace-rb/blob/master/AGENTS.md Lists available gemfiles and their corresponding `BUNDLE_GEMFILE` values, useful for managing different dependency sets. ```bash bundle exec rake dependency:list ``` -------------------------------- ### Configure Rack Instrumentation to Show URL Base Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Configure Datadog's Rack instrumentation to include the URL base (scheme, host, port) in traces. Use `quantize: { base: :show }` for this behavior. ```ruby Datadog.configure do |c| # Show URL base # http://example.com/path?category_id=1&sort_by=asc#featured --> http://example.com/path?category_id&sort_by#featured c.tracing.instrument :rack, quantize: { base: :show } end ``` -------------------------------- ### Manual Instrumentation for Web Requests in Ruby Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Use Datadog::Tracing.trace to manually instrument specific code blocks. This example traces a web request, an ActiveRecord call, and template rendering, adding custom tags to the span. ```ruby get '/posts' do Datadog::Tracing.trace('web.request', service: 'my-blog', resource: 'GET /posts') do |span| # Trace the activerecord call Datadog::Tracing.trace('posts.fetch') do @posts = Posts.order(created_at: :desc).limit(10) end # Add some APM tags span.set_tag('http.method', request.request_method) span.set_tag('posts.count', @posts.length) # Trace the template rendering Datadog::Tracing.trace('template.render') do erb :index end end end ``` -------------------------------- ### Build and Run Integration Tests Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/hanami/README.md Build Docker images for integration tests using a specified Ruby version and then run the tests using the provided script. ```sh ./script/build-images -v ./script/ci -v ``` -------------------------------- ### Configure AWS SDK Instrumentation Source: https://context7.com/datadog/dd-trace-rb/llms.txt Activate instrumentation for the AWS SDK. Requires `Datadog.configure`. ```ruby c.tracing.instrument :aws ``` -------------------------------- ### Propagate Traces Between Threads Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide.md Propagate traces across threads by extracting a TraceDigest in the parent thread and using it to continue the trace in the child thread. Ensure the digest is produced before the thread starts to avoid incorrect parent span association. ```ruby # Get trace digest trace = Datadog::Tracing.active_trace # NOTE: We must produce the digest BEFORE starting the thread. # Otherwise if it's lazily evaluated within the thread, # the thread's trace may follow the wrong parent span. trace_digest = trace.to_digest Thread.new do # Inherits trace properties from the trace digest Datadog::Tracing.trace('my.job', continue_from: trace_digest) do |span, trace| trace.id == trace_digest.trace_id end end ``` -------------------------------- ### Manual Tracing in 0.x vs 1.0 Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/UpgradeGuide.md Illustrates the difference in manual tracing syntax between 0.x and 1.0. In 1.0, the block yields a `Datadog::Tracing::SpanOperation` and `Datadog::Tracing::TraceOperation`. ```ruby ### Old 0.x ### Datadog.tracer.trace('my.job') do |span| # Do work... # span => # end ``` -------------------------------- ### Configure Ethon Tracing with Options Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Instrument the Ethon library to trace HTTP requests. The `**options` argument allows for customization of tracing behavior, such as service name and distributed tracing. ```ruby require 'datadog' Datadog.configure do |c| c.tracing.instrument :ethon, **options end ``` -------------------------------- ### Set Custom Time Provider for Datadog Tracing in Ruby Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Configure a custom time provider for Datadog tracing in Ruby, useful for testing scenarios. This example shows how to use `Time.now_without_mock_time` to ensure the tracer uses the real wall clock for timestamps. ```ruby Datadog.configure do |c| # For Timecop, for example, `->{ Time.now_without_mock_time }` allows the tracer to use the real wall time. c.time_now_provider = -> { Time.now_without_mock_time } end ``` -------------------------------- ### Lint with Zizmor Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DevelopmentGuide.md Run this Docker command to lint code with Zizmor locally if CI fails. Requires a GitHub token and mounts the current directory. ```bash docker run --rm -v $(pwd):/dd-trace-rb -w /dd-trace-rb -e GH_TOKEN=$(gh auth token) ghcr.io/woodruffw/zizmor --min-severity low . ``` -------------------------------- ### Validate Environment Variable Strings with EnvStringValidationCop Source: https://github.com/datadog/dd-trace-rb/blob/master/rubocop/custom_cops/README.md This cop validates environment variable strings (literal strings starting with `DD_` or `OTEL_`) against a list of supported configurations to ensure they are valid and documented. Use `# rubocop:disable CustomCops/EnvStringValidationCop` to handle legitimate false positives. ```ruby # These will trigger offenses if not in the supported configurations: config_value = "DD_CUSTOM_ENV_VAR" settings = { api_key: "DD_NONEXISTENT_KEY" } # OpenTelemetry variables are also checked: otel_config = "OTEL_CUSTOM_SETTING" ``` ```ruby # These are allowed (from supported configurations): api_key = "DD_API_KEY" service_name = "DD_SERVICE" trace_enabled = "DD_TRACE_ENABLED" otel_service = "OTEL_SERVICE_NAME" otel_sampler = "OTEL_TRACES_SAMPLER" ``` ```ruby # False positive: telemetry key that looks like an env var aulemetry_data = { "DD_AGENT_TRANSPORT" => transport_type # rubocop:disable CustomCops/EnvStringValidationCop } # False positive: log message containing env var pattern logger.debug("Processing DD_CUSTOM_METRIC_NAME") # rubocop:disable CustomCops/EnvStringValidationCop ``` -------------------------------- ### Run Rubocop for Code Style and Quality Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/DevelopmentGuide.md Execute this command to check code style and quality using Rubocop. Use the -A flag to automatically fix violations. ```bash bundle exec rake rubocop ``` ```bash bundle exec rake rubocop -A ``` -------------------------------- ### Manually Trace Ruby Code Source: https://github.com/datadog/dd-trace-rb/blob/master/docs/GettingStarted.md Use `Datadog::Tracing.trace` to wrap blocks of code for instrumentation. You can modify the span within the block, for example, to change the resource name or set tags. Ensure `service` and `resource` options are set to avoid spans being discarded. ```ruby Datadog::Tracing.trace(name, **options) do |span, trace| # Wrap this block around the code you want to instrument # Additionally, you can modify the span here. # e.g. Change the resource name, set tags, etc... end ``` -------------------------------- ### Configure Datastore Instrumentation Source: https://context7.com/datadog/dd-trace-rb/llms.txt Enable instrumentation for various datastores including MySQL2, PostgreSQL (pg), Trilogy, MongoDB, Elasticsearch, OpenSearch, and Dalli (Memcached). Options like comment propagation and JSON command tagging are available. Requires `Datadog.configure`. ```ruby c.tracing.instrument :mysql2, comment_propagation: 'service' c.tracing.instrument :pg, comment_propagation: 'service' c.tracing.instrument :trilogy c.tracing.instrument :mongo, json_command: true c.tracing.instrument :elasticsearch c.tracing.instrument :opensearch c.tracing.instrument :dalli # Memcached ``` -------------------------------- ### Build Base Ruby Images Source: https://github.com/datadog/dd-trace-rb/blob/master/integration/apps/ruby/README.md Builds base Docker images for the Ruby demo application. Specify a Ruby version with -v or build for all versions. ```bash script/build-images -v 3.0 ``` ```bash script/build-images ```