본문 바로가기
WIKI 기술 지식 베이스

(레거시) Ruby 애플리케이션 추적 ((Legacy) Tracing Ruby Applications)

원문 보기 위키 갱신

ddtrace는 Ruby용 Datadog 트레이싱 클라이언트예요. 웹 서버, 데이터베이스, 마이크로서비스를 흐르는 요청을 추적해서 개발자가 병목 현상과 문제가 있는 요청을 높은 가시성으로 파악할 수 있게 해줘요.

출처: 문서

본문

경고: 이 문서는 ddtrace gem v1.x용이에요. datadog gem v2.0 이상을 사용하고 있다면 최신 Ruby 애플리케이션 추적 문서를 참고해요.

시작하기 (Getting started)

0.x 버전에서 업그레이드하는 경우에는 업그레이드 가이드를 확인해 보세요.

일반적인 APM 문서는 설정 문서를 참고해요.

애플리케이션이 Datadog에 정보를 보내기 시작한 뒤 APM이 어떤 모습인지 더 알고 싶다면 용어와 개념 문서를 확인해 보세요.

라이브러리 API 문서는 YARD 문서를 참고해요.

기여하고 싶다면 기여 가이드라인과 개발 가이드를 확인해 보세요.

호환성 요구 사항 (Compatibility requirements)

Datadog Ruby 라이브러리의 전체 지원 목록은 호환성 요구 사항을 참고해요.

설치 (Installation)

Ruby 애플리케이션에 추적을 추가하는 일은 몇 단계만 거치면 돼요:

  1. 추적을 위한 Datadog Agent 설정하기
  2. 애플리케이션 계측하기
  3. 애플리케이션을 Datadog Agent에 연결하기

추적을 위한 Datadog Agent 설정 (Setup the Datadog Agent for tracing)

ddtrace을 설치하기 전에, 먼저 Datadog Agent를 설치해 두세요. ddtrace이 추적 데이터를 보낼 대상이에요.

그런 다음 Datadog Agent가 추적을 수락하도록 설정해요. 다음 중 한 가지 방법을 사용하세요:

  • Agent 환경에 DD_APM_ENABLED=true 설정

또는

추가로, 컨테이너 환경에서는…

  • Agent 환경에 DD_APM_NON_LOCAL_TRAFFIC=true 설정

또는

컨테이너 환경에서 Agent가 추적을 수신하도록 구성하려면 Docker, Kubernetes, Amazon ECS, Fargate별 설정 지침을 확인해 보세요.

추적 데이터 수집 설정 (Configuring trace data ingestion)

Datadog Agent는 기본적으로 HTTP를 통해 포트 8126에서 추적을 수신해요.

Agent가 추적 데이터를 수신하는 프로토콜이나 포트는 다음과 같이 변경할 수 있어요.

HTTP over TCP의 경우:

  • Agent 환경에 DD_APM_RECEIVER_PORT=<port> 설정

또는

Unix Domain Socket (UDS)의 경우:

  • DD_APM_RECEIVER_SOCKET=<path-to-socket-file> 설정

또는

애플리케이션 계측 (Instrument your application)

Rails 또는 Hanami 애플리케이션 (Rails or Hanami applications)

  1. Gemfile에 ddtrace gem을 추가해요:

    source 'https://rubygems.org'
    gem 'ddtrace', require: 'ddtrace/auto_instrument'
    
  2. bundle install로 gem을 설치해요

  3. 다음 내용이 담긴 config/initializers/datadog.rb 파일을 만들어요:

    Datadog.configure do |c|
      # Add additional configuration here.
      # Activate integrations, change tracer settings, etc...
    end
    

이 블록을 사용해서 다음과 같이 할 수 있어요:

  • 추가 설정값 추가하기
  • 계측 활성화 또는 재구성하기

기타 Ruby 애플리케이션 (Other Ruby applications)

애플리케이션이 위에서 언급한 지원 gem(Rails 또는 Hanami)을 사용하지 않는다면 다음과 같이 설정할 수 있어요:

  1. Gemfile에 ddtrace gem을 추가해요:

    source 'https://rubygems.org'
    gem 'ddtrace'
    
  2. bundle install로 gem을 설치해요

  3. 계측해야 하는 지원되는 라이브러리나 프레임워크를 require해요.

  4. 애플리케이션에 require 'ddtrace/auto_instrument'을 추가해요. 참고: 이 작업은 지원되는 라이브러리나 프레임워크를 require한 이후에 해야 해요.

    # Example frameworks and libraries
    require 'sinatra'
    require 'faraday'
    require 'redis'
    
    require 'ddtrace/auto_instrument'
    
  5. 애플리케이션에 설정 블록을 추가해요:

    Datadog.configure do |c|
      # Add additional configuration here.
      # Activate integrations, change tracer settings, etc...
    end
    

이 블록을 사용해서 다음과 같이 할 수 있어요:

  • 추가 설정값 추가하기
  • 계측 활성화 또는 재구성하기

OpenTracing 설정 (Configuring OpenTracing)

  1. Gemfile에 ddtrace gem을 추가해요:

    source 'https://rubygems.org'
    gem 'ddtrace'
    
  2. bundle install로 gem을 설치해요

  3. OpenTracing 설정 파일에 다음을 추가해요:

    require 'opentracing'
    require 'datadog/tracing'
    require 'datadog/opentracer'
    
    # Activate the Datadog tracer for OpenTracing
    OpenTracing.global_tracer = Datadog::OpenTracer::Tracer.new
    
  4. 애플리케이션에 설정 블록을 추가해요:

    Datadog.configure do |c|
      # Configure the Datadog tracer here.
      # Activate integrations, change tracer settings, etc...
      # By default without additional configuration,
      # no additional integrations will be traced, only
      # what you have instrumented with OpenTracing.
    end
    

이 블록을 사용해서 다음과 같이 할 수 있어요:

  • 추가 Datadog 설정값 추가하기
  • Datadog 계측 활성화 또는 재구성하기

OpenTelemetry 설정 (Configuring OpenTelemetry)

OTLP를 사용하면 ddtrace 없이도 OpenTelemetry 트레이스를 Datadog Agent로 직접 보낼 수 있어요. 자세한 내용은 Datadog Agent의 OTLP 수집 문서를 확인해 보세요.

애플리케이션을 Datadog Agent에 연결 (Connect your application to the Datadog Agent)

기본적으로 ddtrace은 아래 나열된 우선순위에서 가장 먼저 사용 가능한 설정으로 Agent에 연결해요:

  1. 명시적으로 제공된 설정값(호스트명/포트/전송 방식)
  2. /var/run/datadog/apm.socket에 있는 Unix Domain Socket (UDS)
  3. 127.0.0.1:8126로 HTTP over TCP

Datadog Agent가 이 중 어느 위치에서든 수신 중이라면 추가 설정이 필요하지 않아요.

Agent가 애플리케이션과 다른 호스트나 컨테이너에서 실행 중이거나, 다른 프로토콜로 트레이스를 보내고 싶다면 그에 맞게 애플리케이션을 설정해야 해요.

  • HTTP over TCP로 추적 데이터를 Agent에 보내는 방법
  • Unix Domain Socket (UDS)로 추적 데이터를 Agent에 보내는 방법

설치 마지막 단계 (Final steps for installation)

설정을 마치면 몇 분 안에 서비스가 APM 서비스 페이지에 나타나요. APM UI 사용법에 대해 더 알아보세요.

수동 계측 (Manual Instrumentation)

지원되는 프레임워크 계측을 사용하지 않는다면, 코드를 수동으로 계측하고 싶을 거예요.

Ruby 코드를 추적하려면 Datadog::Tracing.trace 메서드를 사용할 수 있어요:

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

여기서 name은 수행 중인 작업의 일반적인 종류를 설명하는 String이어야 해요 (예: 'web.request', 'request.parse').

그리고 options는 다음 선택적 키워드 인자예요:

Key Type Description Default
autostart Bool 시간 측정을 자동으로 시작할지 여부예요. false면 사용자가 span.start를 호출해야 해요. true
continue_from Datadog::TraceDigest 다른 실행 컨텍스트에서 시작된 트레이스를 이어서 계속해요. TraceDigest가 이어지는 지점을 설명해요. nil
on_error Proc 스팬에서 오류가 발생했을 때 오류 처리 동작을 재정의해요. span과 error를 인자로 받아요. 기본적으로 스팬에 오류를 설정해요. `proc {
resource String 작업 대상이 되는 리소스나 액션의 이름이에요. resource 값이 같은 트레이스는 메트릭을 위해 함께 그룹화돼요(하지만 각각 독립적으로 볼 수 있어요). 보통 URL, 쿼리, 요청 등 도메인 특화 값이에요 (예: 'Article#submit', http://example.com/articles/list.) name of Span.
service String 이 스팬이 속한 서비스 이름이에요 (예: 'my-web-service') Tracer default-service, $PROGRAM_NAME 또는 'ruby'
start_time Time 스팬이 실제로 시작된 시각이에요. 이미 발생한 이벤트를 추적할 때 유용해요. Time.now
tags Hash 스팬에 추가해야 할 추가 태그예요. {}
type String 스팬의 유형이에요 (예: 'http', 'db' 등) nil

최소한 service와 resource는 모두 설정하는 걸 강력히 권장해요. service나 resource가 nil인 스팬은 Datadog Agent가 폐기해요.

수동 계측이 실제로 적용된 예시:

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

비동기 추적 (Asynchronous tracing)

Datadog::Tracing.trace로 코드 블록을 항상 감쌀 수 있는 건 아니에요. 이벤트 기반 또는 알림 기반 계측 중에는 이벤트가 시작되거나 끝날 때만 알려주는 경우가 있어요.

이런 작업을 추적하려면 블록 없이 Datadog::Tracing.trace를 호출해서 코드를 비동기적으로 추적할 수 있어요:

# 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

블록 없이 Datadog::Tracing.trace를 호출하면 시작됐지만 끝나지 않은 Datadog::Tracing::SpanOperation이 반환돼요. 그런 다음 이 스팬을 원하는 대로 수정하고 finish로 닫을 수 있어요.

끝나지 않은 스팬을 남겨두면 안 돼요. 트레이스가 완료될 때 스팬이 열려 있으면 트레이스가 폐기돼요. 이런 일이 벌어질 것 같다면 디버그 모드를 활성화해서 경고를 확인할 수 있어요.

시작/종료 이벤트를 처리할 때 이런 상황을 피하려면 Datadog::Tracing.active_span을 사용해 현재 활성 스팬을 가져올 수 있어요.

# e.g. ActiveSupport::Notifications calls this when an event starts
def start(name, id, payload)
  # Start a span
  Datadog::Tracing.trace(name)
end

# e.g. ActiveSupport::Notifications calls this when an event finishes
def finish(name, id, payload)
  # Retrieve current active span (thread-safe)
  current_span = Datadog::Tracing.active_span
  unless current_span.nil?
    current_span.resource = payload[:query]
    current_span.finish
  end
end

중첩 메서드에서 트레이스 보강 (Enriching traces from nested methods)

어떤 메서드에서든 현재 활성 스팬에 추가 정보를 태그로 붙일 수 있어요. 다만 활성 스팬이 없는 상태에서 메서드가 호출되면 active_span은 nil이 돼요.

# e.g. adding tag to active span

current_span = Datadog::Tracing.active_span
current_span.set_tag('my_tag', 'my_value') unless current_span.nil?

active_trace 메서드로 현재 활성 트레이스를 가져올 수도 있어요. 활성 트레이스가 없으면 nil을 반환해요.

# e.g. accessing active trace

current_trace = Datadog::Tracing.active_trace

통합 계측 (Integration instrumentation)

많은 인기 라이브러리와 프레임워크가 기본적으로 지원되며 자동 계측할 수 있어요. 자동으로 활성화되진 않지만, Datadog.configure API를 사용해 쉽게 활성화하고 설정할 수 있어요:

Datadog.configure do |c|
  # Activates and configures an integration
  c.tracing.instrument :integration_name, **options
end

options는 통합별 설정을 위한 키워드 인자예요.

사용 가능한 통합과 지원 버전 목록은 Ruby 통합 호환성을 참고해요.

사용 가능한 통합의 설정 옵션 목록은 다음을 참고해요:

CI 가시성 (CI Visibility)

Datadog CI Visibility의 경우 다음 Datadog.configure API를 사용해 라이브러리 계측을 활성화하고 설정할 수 있어요:

Datadog.configure do |c|
  # Activates and configures an integration
  c.ci.instrument :integration_name, **options
end

options는 통합별 설정을 위한 키워드 인자예요.

사용 가능한 통합과 지원 버전 목록은 Ruby CI 통합 호환성을 참고해요.

Action Cable

Action Cable 통합은 브로드캐스트 메시지와 채널 액션을 추적해요.

Datadog.configure로 활성화할 수 있어요:

require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :action_cable
end

Action Mailer

Action Mailer 통합은 Rails 5 ActionMailer 액션에 대한 추적을 제공해요.

Datadog.configure로 활성화할 수 있어요:

require 'ddtrace'
Datadog.configure do |c|
  c.tracing.instrument :action_mailer, **options
end

options는 다음 키워드 인자예요:

Key Description Default
email_data action_mailer.deliver 스팬에 추가 이메일 페이로드 메타데이터를 추가할지 여부예요. 필드에는 ['subject', 'to', 'from', 'bcc', 'cc', 'date', 'perform_deliveries']가 있어요. false

Action Pack

대부분의 경우 Action Pack은 Rails의 일부로 설정되지만, 별도로도 활성화할 수 있어요:

require 'actionpack'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :action_pack
end

Action View

대부분의 경우 Action View는 Rails의 일부로 설정되지만, 별도로도 활성화할 수 있어요:

require 'actionview'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :action_view, **options
end

options는 다음 키워드 인자예요:

Key Description Default
template_base_path 템플릿 이름을 파싱할 때 사용돼요. 템플릿을 views/ 폴더에 저장하지 않는다면 이 값을 변경해야 할 수도 있어요 'views/'

Active Job

대부분의 경우 Active Job은 Rails의 일부로 설정되지만, 별도로도 활성화할 수 있어요:

require 'active_job'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :active_job
end

ExampleJob.perform_later

Active Model Serializers

Active Model Serializers 통합은 0.9+ 버전의 serialize 이벤트와 0.10+ 버전의 render 이벤트를 추적해요.

require 'active_model_serializers'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :active_model_serializers
end

my_object = MyModel.new(name: 'my object')
ActiveModelSerializers::SerializableResource.new(test_obj).serializable_hash

Active Record

대부분의 경우 Active Record는 웹 프레임워크(Rails, Sinatra…)의 일부로 설정되지만, 단독으로도 설정할 수 있어요:

require 'tmpdir'
require 'sqlite3'
require 'active_record'
require 'ddtrace'

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

options는 다음 키워드 인자예요:

Key Description Default
service_name SQL 쿼리 계측의 서비스 이름을 덮어써요. ActiveRecord 인스턴스화 계측은 항상 애플리케이션에 설정된 서비스 이름을 사용해요. 데이터베이스 어댑터 이름 (예: 'mysql2')

데이터베이스별 트레이스 설정

describes 옵션을 사용해 데이터베이스 연결별로 트레이스 설정을 구성할 수 있어요:

# 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.tracing.instrument :active_record, describes: :secondary_database, service_name: 'secondary-db'

  # Block configuration pattern.
  c.tracing.instrument :active_record, describes: :secondary_database do |second_db|
    second_db.service_name = 'secondary-db'
  end

  # Connection string with the following connection settings:
  # adapter, username, host, port, database
  # Other fields are ignored.
  c.tracing.instrument :active_record, describes: 'mysql2://[email protected]:3306/mysql', service_name: 'secondary-db'

  # Hash with following connection settings:
  # adapter, username, host, port, database
  # Other fields are ignored.
  c.tracing.instrument :active_record, describes: {
      adapter:  'mysql2',
      host:     '127.0.0.1',
      port:     '3306',
      database: 'mysql',
      username: 'root'
    },
    service_name: 'secondary-db'

  # If using the `makara` gem, it's possible to match on connection `role`:
  c.tracing.instrument :active_record, describes: { makara_role: 'primary' }, service_name: 'primary-db'
  c.tracing.instrument :active_record, describes: { makara_role: 'replica' }, service_name: 'secondary-db'
end

데이터베이스 연결 필드의 부분 일치를 기반으로 설정을 만들 수도 있어요:

Datadog.configure do |c|
  # Matches any connection on host `127.0.0.1`.
  c.tracing.instrument :active_record, describes: { host:  '127.0.0.1' }, service_name: 'local-db'

  # Matches any `mysql2` connection.
  c.tracing.instrument :active_record, describes: { adapter: 'mysql2'}, service_name: 'mysql-db'

  # Matches any `mysql2` connection to the `reports` database.
  #
  # In case of multiple matching `describe` configurations, the latest one applies.
  # In this case a connection with both adapter `mysql` and database `reports`
  # will be configured `service_name: 'reports-db'`, not `service_name: 'mysql-db'`.
  c.tracing.instrument :active_record, describes: { adapter: 'mysql2', database:  'reports'}, service_name: 'reports-db'
end

여러 describes 설정이 연결과 일치하면 마지막으로 설정된 일치 규칙이 적용돼요.

ActiveRecord가 describes가 정의한 키와 일치하는 연결을 사용하는 이벤트를 추적하면, 그 연결에 할당된 트레이스 설정을 사용해요. 연결이 설명된 어떤 연결과도 일치하지 않으면 대신 c.tracing.instrument :active_record가 정의한 기본 설정을 사용해요.

Active Support

대부분의 경우 Active Support는 Rails의 일부로 설정되지만, 별도로도 활성화할 수 있어요:

require 'activesupport'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :active_support, **options
end

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

options는 다음 키워드 인자예요:

Key Description Default
cache_service active_support 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 active_support-cache

AWS

AWS 통합은 AWS 서비스(S3, ElastiCache 등)와의 모든 상호작용(예: API 호출)을 추적해요.

require 'aws-sdk'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :aws, **options
end

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

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_AWS_SERVICE_NAME aws 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 aws
peer_service DD_TRACE_AWS_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil

Concurrent Ruby

Concurrent Ruby 통합은 ::Concurrent::Future와 Concurrent::Async를 사용할 때 컨텍스트 전파를 지원하고, Future#execute와 Concurrent::Async#async 내부에서 추적된 코드가 올바른 부모를 갖도록 보장해요.

통합을 활성화하려면 Datadog.configure 메서드를 사용해요:

# Inside Rails initializer or equivalent
Datadog.configure do |c|
  # Patches ::Concurrent::Future to use ExecutorService that propagates context
  c.tracing.instrument :concurrent_ruby
end

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

# Pass context into code executed within Concurrent::Async
class MyClass
  include ConcurrentAsync

  def foo
    Datadog::Tracing.trace('inner') { }
  end
end

Datadog::Tracing.trace('outer') do
  MyClass.new.async.foo
end

Cucumber

Cucumber 통합은 cucumber 프레임워크를 사용할 때 모든 시나리오와 단계의 실행을 추적해요.

통합을 활성화하려면 Datadog.configure 메서드를 사용해요:

require 'cucumber'
require 'ddtrace'

# Configure default Cucumber integration
Datadog.configure do |c|
  c.ci.instrument :cucumber, **options
end

# Example of how to attach tags from scenario to active span
Around do |scenario, block|
  active_span = Datadog.configuration[:cucumber][:tracer].active_span
  unless active_span.nil?
    scenario.tags.filter { |tag| tag.include? ':' }.each do |tag|
      active_span.set_tag(*tag.name.split(':', 2))
    end
  end
  block.call
end

options는 다음 키워드 인자예요:

Key Description Default
enabled Cucumber 테스트를 추적할지 여부를 정의해요. 추적을 일시적으로 비활성화하는 데 유용해요. true 또는 false true
service_name cucumber 계측에 사용되는 서비스 이름이에요. 'cucumber'
operation_name cucumber 계측에 사용되는 작업 이름이에요. trace.#{operation_name}.errors 같은 자동 트레이스 메트릭 이름을 바꾸고 싶을 때 유용해요. 'cucumber.test'

Dalli

Dalli 통합은 memcached 서버로의 모든 호출을 추적해요:

require 'dalli'
require 'ddtrace'

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

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

options는 다음 키워드 인자예요:

Key Env Var Description Default
command_enabled DD_TRACE_MEMCACHED_COMMAND_ENABLED 명령을 memcached.command 태그로 수집해요. 명령 key는 잠재적으로 민감한 정보를 포함할 수 있어요. false
service_name DD_TRACE_DALLI_SERVICE_NAME dalli 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 memcached
peer_service DD_TRACE_DALLI_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil

DelayedJob

DelayedJob 통합은 라이프사이클 훅을 사용해 작업 실행과 enqueue를 추적해요.

Datadog.configure로 활성화할 수 있어요:

require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :delayed_job, **options
end

options는 다음 키워드 인자예요:

Key Description Default
error_handler 작업에서 오류가 발생했을 때 호출되는 사용자 지정 오류 처리기예요. span과 error를 인자로 받아요. 기본적으로 스팬에 오류를 설정해요. 일시적인 오류를 무시하는 데 유용해요. `proc {

Elasticsearch

Elasticsearch 통합은 Client 객체에서 perform_request에 대한 모든 호출을 추적해요:

require 'elasticsearch/transport'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :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'

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

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_ELASTICSEARCH_SERVICE_NAME elasticsearch 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 elasticsearch
peer_service DD_TRACE_ELASTICSEARCH_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
quantize 양자화 옵션을 담은 해시예요. 양자화하지 않을 키의 :show Array(또는 양자화를 건너뛸 :all), 또는 완전히 제외할 키의 :exclude Array를 포함할 수 있어요. {}

Ethon

ethon 통합은 Easy 또는 Multi 객체를 통한 모든 HTTP 요청을 추적해요. 이 통합은 Ethon 기반의 Typhoeus 라이브러리도 지원해요.

require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :ethon, **options

  # optionally, specify a different service name for hostnames matching a regex
  c.tracing.instrument :ethon, describes: /user-[^.]+\\.example\\.com/ do |ethon|
    ethon.service_name = 'user.example.com'
    ethon.split_by_domain = false # Only necessary if split_by_domain is true by default
  end
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_ETHON_SERVICE_NAME ethon 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 ethon
peer_service DD_TRACE_ETHON_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
split_by_domain true로 설정하면 요청 도메인을 서비스 이름으로 사용해요. false

Excon

excon 통합은 ddtrace 미들웨어를 통해 사용할 수 있어요:

require 'excon'
require 'ddtrace'

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

  # optionally, specify a different service name for hostnames matching a regex
  c.tracing.instrument :excon, describes: /user-[^.]+\\.example\\.com/ do |excon|
    excon.service_name = 'user.example.com'
    excon.split_by_domain = false # Only necessary if split_by_domain is true by default
  end
end

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

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_EXCON_SERVICE_NAME excon 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 excon
peer_service DD_TRACE_EXCON_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
split_by_domain true로 설정하면 요청 도메인을 서비스 이름으로 사용해요. false
error_handler response 매개변수를 받는 Proc이에요. truthy 값으로 평가되면 트레이스 스팬이 오류로 표시돼요. 기본적으로 5XX 응답만 오류로 설정해요. nil

다른 설정을 사용하도록 연결 구성

Excon으로 여러 연결을 사용한다면, 각각의 생성자를 미들웨어로 구성해 서로 다른 설정을 줄 수 있어요:

# Wrap the Datadog tracing middleware around the default middleware stack
Excon.new(
  'http://example.com',
  middlewares: Datadog::Tracing::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::Tracing::Contrib::Excon::Middleware.with(options),
    Excon::Middleware::Idempotent
  ]
)

여기서 options는 위 표에 있는 매개변수 중 아무거나 담은 Hash예요.

Faraday

faraday 통합은 ddtrace 미들웨어를 통해 사용할 수 있어요:

require 'faraday'
require 'ddtrace'

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

  # optionally, specify a different service name for hostnames matching a regex
  c.tracing.instrument :faraday, describes: /user-[^.]+\\.example\\.com/ do |faraday|
    faraday.service_name = 'user.example.com'
    faraday.split_by_domain = false # Only necessary if split_by_domain is true by default
  end
end

# In case you want to override the global configuration for a certain client instance
connection = Faraday.new('https://example.com') do |builder|
  builder.use(:ddtrace, **options)
  builder.adapter Faraday.default_adapter
end

connection.get('/foo')

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_FARADAY_SERVICE_NAME faraday 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 faraday
peer_service DD_TRACE_FARADAY_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
split_by_domain true로 설정하면 요청 도메인을 서비스 이름으로 사용해요. false
error_handler response 매개변수를 받는 Proc이에요. truthy 값으로 평가되면 트레이스 스팬이 오류로 표시돼요. 기본적으로 5XX 응답만 오류로 설정해요. nil
on_error 요청에서 오류가 발생했을 때 호출되는 사용자 지정 오류 처리기예요. span과 error를 인자로 받아요. 기본적으로 스팬에 오류를 설정해요. `proc { span, error

Grape

Grape 통합은 Grape 엔드포인트와 필터에 계측을 추가해요. 이 통합은 Rack, Rails 같은 다른 통합과 나란히 작동할 수 있어요.

통합을 활성화하려면 Grape 애플리케이션을 정의하기 전에 Datadog.configure 메서드를 사용해요:

# api.rb
require 'grape'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :grape, **options
end

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

options는 다음 키워드 인자예요:

Key Env Var Description Default
enabled DD_TRACE_GRAPE_ENABLED Grape를 추적할지 여부를 정의해요. 추적을 일시적으로 비활성화하는 데 유용해요. true 또는 false true
error_statuses 오류로 표시해야 할 상태 코드 또는 상태 코드 범위를 정의해요. '404,405,500-599' 또는 [404,405,'500-599'] nil

GraphQL

GraphQL 통합은 GraphQL 쿼리에 대한 계측을 활성화해요.

통합을 활성화하려면 Datadog.configure 메서드를 사용해요:

# Inside Rails initializer or equivalent
Datadog.configure do |c|
  c.tracing.instrument :graphql, schemas: [YourSchema], **options
end

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

instrument :graphql 메서드는 다음 매개변수를 받아들여요. options 자리에 추가 옵션을 넣을 수 있어요:

Key Description Default
schemas 필수. 추적할 GraphQL::Schema 객체의 배열이에요. 나열된 모든 스키마에 이 구성에 제공된 옵션을 사용해 추적이 추가돼요. 제공하지 않으면 추적이 활성화되지 않아요. []
service_name graphql 계측에 사용되는 서비스 이름이에요 'ruby-graphql'

GraphQL 스키마 수동 구성

스키마에 대한 추적기 설정을 개별적으로 구성하고 싶다면(예: 서로 다른 서비스 이름을 가진 여러 스키마), 스키마 정의에서 GraphQL API를 사용해 다음을 추가할 수 있어요:

# Class-based schema
class YourSchema < GraphQL::Schema
  use(
    GraphQL::Tracing::DataDogTracing,
    service: 'graphql'
  )
end
# .define-style schema
YourSchema = GraphQL::Schema.define do
  use(
    GraphQL::Tracing::DataDogTracing,
    service: 'graphql'
  )
end

또는 이미 정의된 스키마를 수정할 수 있어요:

# Class-based schema
YourSchema.use(
    GraphQL::Tracing::DataDogTracing,
    service: 'graphql'
)
# .define-style schema
YourSchema.define do
  use(
    GraphQL::Tracing::DataDogTracing,
    service: 'graphql'
  )
end

수동으로 구성하기로 했다면 이중 추적을 피하기 위해 Datadog.configure에서 instrument :graphql을 하지 마세요. 이 두 가지 GraphQL 추적 구성 방식은 상호 배타적인 것으로 간주돼요.

gRPC

grpc 통합은 서비스의 원격 프로시저 호출을 실행하기 전에 미들웨어로 작동하는 클라이언트와 서버 인터셉터를 모두 추가해요. gRPC 애플리케이션은 보통 분산되어 있으므로, 이 통합은 클라이언트와 서버 간에 추적 정보를 공유해요.

통합을 설정하려면 Datadog.configure 메서드를 이렇게 사용해요:

require 'grpc'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :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!'))

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_GRPC_SERVICE_NAME grpc 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 grpc
peer_service DD_TRACE_GRPC_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
server_error_handler 서버 오류가 있을 때 호출되는 사용자 지정 오류 처리기예요. span과 error 매개변수를 받는 Proc이에요. 기본적으로 스팬에 오류를 설정해요. `proc { span, error
client_error_handler 클라이언트 오류가 있을 때 호출되는 사용자 지정 오류 처리기예요. span과 error 매개변수를 받는 Proc이에요. 기본적으로 스팬에 오류를 설정해요. `proc { span, error

폐기 예정 공지:

  • error_handler는 제거될 거예요. 대신 server_error_handler를 사용해요.

다른 설정을 사용하도록 클라이언트 구성

여러 클라이언트가 여러 고유한 서비스를 호출하는 상황에서는 Datadog 인터셉터를 직접 전달할 수 있어요:

configured_interceptor = Datadog::Tracing::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]
)

이 통합은 configured_interceptor가 그 클라이언트 인스턴스에 대해 고유한 추적 설정을 수립하도록 보장해요.

hanami

hanami 통합은 hanami 애플리케이션의 라우팅, 액션, 렌더를 계측해요. hanami 계측을 활성화하려면 다음과 같이 자동 계측을 권장해요:

gem 'ddtrace', require: 'ddtrace/auto_instrument'

그리고 config/initializers 폴더에 initializer 파일을 만들어요:

# config/initializers/datadog.rb
Datadog.configure do |c|
  c.tracing.instrument :hanami, **options
end

options는 다음 키워드 인자예요:

Key Description Default
service_name hanami 계측의 서비스 이름이에요. nil

http.rb

http.rb 통합은 Http.rb gem을 사용한 모든 HTTP 호출을 추적해요.

require 'http'
require 'ddtrace'
Datadog.configure do |c|
  c.tracing.instrument :httprb, **options
  # optionally, specify a different service name for hostnames matching a regex
  c.tracing.instrument :httprb, describes: /user-[^.]+\\.example\\.com/ do |httprb|
    httprb.service_name = 'user.example.com'
    httprb.split_by_domain = false # Only necessary if split_by_domain is true by default
  end
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_HTTPRB_SERVICE_NAME httprb 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 httprb
peer_service DD_TRACE_HTTPRB_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
split_by_domain true로 설정하면 요청 도메인을 서비스 이름으로 사용해요. false
error_status_codes DD_TRACE_HTTPCLIENT_ERROR_STATUS_CODES 오류로 추적해야 할 HTTP 상태 코드의 범위 또는 배열이에요. 400...600

httpclient

httpclient 통합은 httpclient gem을 사용한 모든 HTTP 호출을 추적해요.

require 'httpclient'
require 'ddtrace'
Datadog.configure do |c|
  c.tracing.instrument :httpclient, **options
  # optionally, specify a different service name for hostnames matching a regex
  c.tracing.instrument :httpclient, describes: /user-[^.]+\\.example\\.com/ do |httpclient|
    httpclient.service_name = 'user.example.com'
    httpclient.split_by_domain = false # Only necessary if split_by_domain is true by default
  end
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_HTTPCLIENT_SERVICE_NAME httpclient 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 httpclient
peer_service DD_TRACE_HTTPCLIENT_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
split_by_domain true로 설정하면 요청 도메인을 서비스 이름으로 사용해요. false
error_status_codes DD_TRACE_HTTPCLIENT_ERROR_STATUS_CODES 오류로 추적해야 할 HTTP 상태 코드의 범위 또는 배열이에요. 400...600

httpx

httpx는 ddtrace과의 자체 통합을 유지하고 있어요:

require "ddtrace"
require "httpx/adapters/datadog"

Datadog.configure do |c|
  c.tracing.instrument :httpx

  # optionally, specify a different service name for hostnames matching a regex
  c.tracing.instrument :httpx, 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

Kafka

Kafka 통합은 ruby-kafka gem에 대한 추적을 제공해요:

Datadog.configure로 활성화할 수 있어요:

require 'active_support/notifications' # required to enable 'ruby-kafka' instrumentation
require 'kafka'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :kafka
end

Minitest

Minitest 통합은 minitest 테스트 프레임워크를 사용할 때 모든 테스트의 실행을 추적해요.

통합을 활성화하려면 Datadog.configure 메서드를 사용해요:

require 'minitest'
require 'ddtrace'

# Configure default Minitest integration
Datadog.configure do |c|
  c.ci.instrument :minitest, **options
end

options는 다음 키워드 인자예요:

Key Description Default
enabled Minitest 테스트를 추적할지 여부를 정의해요. 추적을 일시적으로 비활성화하는 데 유용해요. true 또는 false true
service_name minitest 계측에 사용되는 서비스 이름이에요. 'minitest'
operation_name minitest 계측에 사용되는 작업 이름이에요. trace.#{operation_name}.errors 같은 자동 트레이스 메트릭 이름을 바꾸고 싶을 때 유용해요. 'minitest.test'

MongoDB

이 통합은 MongoDB Ruby Driver에서 MongoDB 클러스터로 보내진 모든 Command를 추적해요. 따라서 Mongoid 같은 Object Document Mapper(ODM)도 공식 Ruby 드라이버를 사용한다면 자동으로 계측돼요. 통합을 활성화하려면 다음처럼 해요:

require 'mongo'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :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_onto(client, **options)

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_MONGO_SERVICE_NAME mongo 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 mongodb
peer_service DD_TRACE_MONGO_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
quantize 양자화 옵션을 담은 해시예요. 양자화하지 않을 키의 :show Array(또는 양자화를 건너뛸 :all), 또는 완전히 제외할 키의 :exclude Array를 포함할 수 있어요. { show: [:collection, :database, :operation] }

연결별 트레이스 설정 구성

describes 옵션을 사용해 연결별로 트레이스 설정을 구성할 수 있어요:

# 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|
  # 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

여러 describes 설정이 연결과 일치하면 마지막으로 설정된 일치 규칙이 적용돼요.

MySQL2

MySQL2 통합은 mysql2 gem을 통해 보내진 모든 SQL 명령을 추적해요.

require 'mysql2'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :mysql2, **options
end

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

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_MYSQL2_SERVICE_NAME mysql2 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 mysql2
peer_service DD_TRACE_MYSQL2_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
comment_propagation DD_DBM_PROPAGATION_MODE 데이터베이스 모니터링을 위한 SQL 주석 전파 모드예요 (예: disabled | service| full).중요: SQL 주석 전파를 활성화하면 잠재적으로 기밀 데이터(서비스 이름)가 데이터베이스에 저장되어, 데이터베이스 접근 권한이 부여된 제3자가 접근할 수 있게 됩니다. 'disabled'
on_error MySQL에서 오류가 발생했을 때 호출되는 사용자 지정 오류 처리기예요. span과 error를 인자로 받아요. 기본적으로 스팬에 오류를 설정해요. 애플리케이션 레벨에서 처리되는 오류를 무시하는 데 유용해요. `proc { span, error

Presto

Presto 통합은 presto-client gem을 통해 보내진 모든 SQL 명령을 추적해요.

require 'presto-client'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :presto, **options
end

client = Presto::Client.new(
  server: "localhost:8880",
  ssl: {verify: false},
  catalog: "native",
  schema: "default",
  time_zone: "US/Pacific",
  language: "English",
  http_debug: true,
)

client.run("select * from system.nodes")

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_PRESTO_SERVICE_NAME presto 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 presto
peer_service DD_TRACE_PRESTO_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil

Qless

Qless 통합은 라이프사이클 훅을 사용해 작업 실행을 추적해요.

Qless 작업에 추적을 추가하려면:

require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :qless, **options
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
tag_job_data DD_QLESS_TAG_JOB_DATA 작업 인자로 태깅을 활성화해요. true면 켜고 false면 꺼요. false
tag_job_tags DD_QLESS_TAG_JOB_TAGS 작업 태그로 태깅을 활성화해요. true면 켜고 false면 꺼요. false

Que

Que 통합은 작업 실행을 추적하는 미들웨어예요.

Datadog.configure로 활성화할 수 있어요:

require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :que, **options
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
enabled DD_TRACE_QUE_ENABLED Que를 추적할지 여부를 정의해요. 추적을 일시적으로 비활성화하는 데 유용해요. true 또는 false true
tag_args DD_TRACE_QUE_TAG_ARGS_ENABLED 작업의 args 필드 태깅을 활성화해요. true면 켜고 false면 꺼요. false
tag_data DD_TRACE_QUE_TAG_DATA_ENABLED 작업의 data 필드 태깅을 활성화해요. true면 켜고 false면 꺼요. false
error_handler 작업에서 오류가 발생했을 때 호출되는 사용자 지정 오류 처리기예요. span과 error를 인자로 받아요. 기본적으로 스팬에 오류를 설정해요. 일시적인 오류를 무시하는 데 유용해요. `proc { span, error

Racecar

Racecar 통합은 Racecar 작업에 대한 추적을 제공해요.

Datadog.configure로 활성화할 수 있어요:

require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :racecar, **options
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_RACECAR_SERVICE_NAME racecar 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 racecar

Rack

Rack 통합은 요청이 기반 프레임워크나 애플리케이션에 도달하기 전에 모든 요청을 추적하는 미들웨어를 제공해요. Rack 최소 인터페이스에 응답하며, Rack 레벨에서 검색할 수 있는 합리적인 값을 제공해요.

이 통합은 Rails 같은 웹 프레임워크와 함께 자동으로 활성화돼요. 일반 Rack 애플리케이션을 사용한다면 config.ru에서 통합을 활성화해요:

# config.ru example
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :rack, **options
end

use Datadog::Tracing::Contrib::Rack::TraceMiddleware

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

run app

options는 다음 키워드 인자예요:

Key Description Default
application Rack 애플리케이션이에요. middleware_names에 필요해요. nil
distributed_tracing 추적 헤더를 받으면 이 서비스 트레이스가 다른 서비스의 트레이스와 연결되도록 분산 추적을 활성화해요 true
headers rack.request에 태그로 추가할 HTTP 요청 또는 응답 헤더의 해시예요. Array 값을 가진 request와 response 키를 받아요 (예: ['Last-Modified']). 각각 http.request.headers.*와 http.response.headers.* 태그를 추가해요. 이 옵션은 전역 DD_TRACE_HEADER_TAGS를 덮어써요. 자세한 내용은 루트 스팬에 헤더 태그 적용을 참고해요. { response: ['Content-Type', 'X-Request-ID'] }
middleware_names rack 스팬의 리소스 이름으로 마지막으로 실행된 미들웨어 클래스를 사용하고 싶으면 이 기능을 활성화해요. rails 계측과 함께 활성화하면, 해당될 때 rack 리소스 이름이 활성 rails 컨트롤러로 설정되어 rails가 우선해요. application 옵션이 필요해요. false
quantize 양자화 옵션을 담은 해시예요. :query 또는 :fragment를 포함할 수 있어요. {}
quantize.base URL 기본부(scheme, host, port)의 동작을 정의해요. http.url 태그에 URL 기본부를 유지하고 http.base_url 태그를 설정하지 않는 :show이거나, 기본적으로 http.url 태그에서 URL 기본부를 제거하고 경로만 남기며 http.base_url을 설정하는 nil일 수 있어요. 옵션은 quantize 옵션 안에 중첩해야 해요. nil
quantize.query URL 양자화의 쿼리 부분에 대한 옵션을 담은 해시예요. :show 또는 :exclude를 포함할 수 있어요. 아래 옵션을 참고해요. 옵션은 quantize 옵션 안에 중첩해야 해요. {}
quantize.query.show 항상 표시해야 하는 값을 정의해요. 문자열의 Array, 모든 값을 표시할 :all, 또는 값을 표시하지 않을 nil일 수 있어요. 옵션은 query 옵션 안에 중첩해야 해요. nil
quantize.query.exclude 완전히 제거해야 하는 값을 정의해요. 문자열의 Array, 쿼리 문자열을 완전히 제거할 :all, 또는 아무것도 제외하지 않을 nil일 수 있어요. 옵션은 query 옵션 안에 중첩해야 해요. nil
quantize.query.obfuscate 쿼리 문자열 수정(redaction) 동작을 정의해요. 옵션의 해시, 기본 내부 난독화 설정을 사용할 :internal, 또는 난독화를 비활성화할 nil일 수 있어요. 난독화는 키-값 연산이 아니라 문자열 단위 연산이라는 점에 유의해요. 활성화되면 query.show는 설정하지 않았다면 기본적으로 :all이 돼요. 옵션은 query 옵션 안에 중첩해야 해요. nil
quantize.query.obfuscate.with 난독화된 일치 항목을 대체할 문자열을 정의해요. String일 수 있어요. 옵션은 query.obfuscate 옵션 안에 중첩해야 해요. '<redacted>'
quantize.query.obfuscate.regex 쿼리 문자열을 수정할 정규식을 정의해요. Regexp이거나, 잘 알려진 민감 데이터를 수정하는 기본 내부 Regexp를 사용할 :internal일 수 있어요. 각 일치 항목은 query.obfuscate.with로 대체되어 완전히 수정돼요. 옵션은 query.obfuscate 옵션 안에 중첩해야 해요. :internal
quantize.fragment URL 프래그먼트의 동작을 정의해요. URL 프래그먼트를 표시할 :show이거나 프래그먼트를 제거할 nil일 수 있어요. 옵션은 quantize 옵션 안에 중첩해야 해요. nil
request_queuing 프론트엔드 서버의 대기열에서 보낸 HTTP 요청 시간을 추적해요. 설정 방법은 HTTP 요청 대기열 처리를 참고해요. false
web_service_name 프론트엔드 서버 요청 대기열 스팬의 서비스 이름이에요 (예: 'nginx') 'web-server'

폐기 예정 공지:

  • quantize.base의 기본값은 향후 버전에서 :exclude에서 :show로 바뀔 거예요. 자발적으로 :show로 옮기는 걸 권장해요.
  • quantize.query.show의 기본값은 향후 버전에서 :all로 바뀌고, quantize.query.obfuscate는 :internal로 바뀔 거예요. 자발적으로 이 미래 값들로 옮기는 걸 권장해요.

URL 양자화 동작 구성

Datadog.configure do |c|
  # Default behavior: all values are quantized, base is removed, fragment is removed.
  # http://example.com/path?category_id=1&sort_by=asc#featured --> /path?category_id&sort_by
  # http://example.com:8080/path?categories[]=1&categories[]=2 --> /path?categories[]

  # Remove URL base (scheme, host, port)
  # http://example.com/path?category_id=1&sort_by=asc#featured --> /path?category_id&sort_by#featured
  c.tracing.instrument :rack, quantize: { base: :exclude }

  # 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 }

  # Show values for any query string parameter matching 'category_id' exactly
  # http://example.com/path?category_id=1&sort_by=asc#featured --> /path?category_id=1&sort_by
  c.tracing.instrument :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 --> /path?category_id=1&sort_by=asc
  c.tracing.instrument :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 --> /path?category_id
  c.tracing.instrument :rack, quantize: { query: { exclude: ['sort_by'] } }

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

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

  # Obfuscate query string, defaulting to showing all values
  # http://example.com/path?password=qwerty&sort_by=asc#featured --> /path?<redacted>&sort_by=asc
  c.tracing.instrument :rack, quantize: { query: { obfuscate: {} } }

  # Obfuscate query string using the provided regex, defaulting to showing all values
  # http://example.com/path?category_id=1&sort_by=asc#featured --> /path?<redacted>&sort_by=asc
  c.tracing.instrument :rack, quantize: { query: { obfuscate: { regex: /category_id=\\d+/ } } }

  # Obfuscate query string using a custom redaction string
  # http://example.com/path?password=qwerty&sort_by=asc#featured --> /path?REMOVED&sort_by=asc
  c.tracing.instrument :rack, quantize: { query: { obfuscate: { with: 'REMOVED' } } }
end

Rails

Rails 통합은 요청, 데이터베이스 호출, 템플릿 렌더링, 캐시 읽기/쓰기/삭제 작업을 추적해요. 이 통합은 Active Support 계측을 활용해 Notification API를 수신하므로, API로 계측된 모든 작업이 추적돼요.

Rails 계측을 활성화하려면 config/initializers 폴더에 initializer 파일을 만들어요:

# config/initializers/datadog.rb
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :rails, **options
end

options는 다음 키워드 인자예요:

Key Description Default
distributed_tracing 추적 헤더를 받으면 이 서비스 트레이스가 다른 서비스의 트레이스와 연결되도록 분산 추적을 활성화해요 true
request_queuing 프론트엔드 서버의 대기열에서 보낸 HTTP 요청 시간을 추적해요. 설정 방법은 HTTP 요청 대기열 처리를 참고해요. false
middleware Rails 애플리케이션에 트레이스 미들웨어를 추가해요. 미들웨어를 로드하고 싶지 않으면 false로 설정해요. true
middleware_names 단락된 미들웨어 요청이 트레이스의 리소스로 미들웨어 이름을 표시하도록 활성화해요. false
service_name 애플리케이션 요청을 추적할 때 사용되는 서비스 이름 (on the rack level) '<app_name>' (Rails 애플리케이션 네임스페이스에서 추론)
template_base_path 템플릿 이름을 파싱할 때 사용돼요. 템플릿을 views/ 폴더에 저장하지 않는다면 이 값을 변경해야 할 수도 있어요 'views/'

지원 버전

MRI Versions JRuby Versions Rails Versions
2.1 3.2 - 4.2
2.2 - 2.3 3.2 - 5.2
2.4 4.2.8 - 5.2
2.5 4.2.8 - 6.1
2.6 - 2.7 9.2 5.0 - 6.1
3.0 - 3.2 6.1

Rake

rake 통합을 활성화하고 계측할 Rake 작업의 목록을 제공하면 Rake 작업 주변에 계측을 추가할 수 있어요.

오래 실행되는 Rake 작업은 계측하지 마세요. 그런 작업은 작업이 끝날 때까지 플러시되지 않는 큰 트레이스를 메모리에 축적할 수 있어요.

오래 실행되는 작업에는 반복 코드 경로 주변에 수동 계측을 사용해요.

Rake 작업 추적을 활성화하려면 Rakefile에 다음을 추가해요:

# At the top of your Rakefile:
require 'rake'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :rake, tasks: ['my_task'], **options
end

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

Rake::Task['my_task'].invoke

options는 다음 키워드 인자예요:

Key Description Default
enabled Rake 작업을 추적할지 여부를 정의해요. 추적을 일시적으로 비활성화하는 데 유용해요. true 또는 false true
quantize 작업 인자의 양자화 옵션을 담은 해시예요. 자세한 내용과 예시는 아래를 참고해요. {}
service_name rake 계측에 사용되는 서비스 이름 'rake'
tasks 계측할 Rake 작업의 이름 []

작업 양자화 동작 구성

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.tracing.instrument :rake

  # Show values for any argument matching :two exactly
  # `rake.invoke.args` tag  --> ['?']
  # `rake.execute.args` tag --> { one: '?', two: 'bar', three: '?' }
  c.tracing.instrument :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.tracing.instrument :rake, quantize: { args: { show: :all } }

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

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

Redis

Redis 통합은 단순 호출과 파이프라인을 모두 추적해요.

require 'redis'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :redis, **options
end

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

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_REDIS_SERVICE_NAME redis 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 redis
peer_service DD_TRACE_REDIS_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
command_args DD_REDIS_COMMAND_ARGS 명령 인자를(예: GET key의 key) 리소스 이름과 태그로 표시해요. false면 명령 이름만 표시돼요 (예: GET). false

인스턴스별 트레이스 설정 구성

Redis 버전 >= 5인 경우:

require 'redis'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :redis # Enabling integration instrumentation is still required
end

customer_cache = Redis.new(custom: { datadog: { service_name: 'custom-cache' } })
invoice_cache = Redis.new(custom: { datadog: { 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(...)

독립형 RedisClient인 경우:

require "redis-client"
require "ddtrace"

redis = RedisClient.config(custom: { datadog: { service_name: "my-custom-redis" } }).new_client

Datadog.configure do |c|
  c.tracing.instrument :redis # Enabling integration instrumentation is still required
end

redis.call('PING')

Redis 버전 < 5인 경우:

require 'redis'
require 'ddtrace'

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(...)

연결별 트레이스 설정 구성

describes 옵션을 사용해 연결별로 트레이스 설정을 구성할 수 있어요:

# 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|
  # The default configuration for any redis client
  c.tracing.instrument :redis, service_name: 'redis-default'

  # The configuration matching a given unix socket.
  c.tracing.instrument :redis, describes: { url: 'unix://path/to/file' }, service_name: 'redis-unix'

  # For network connections, only these fields are considered during matching:
  # scheme, host, port, db
  # Other fields are ignored.

  # Network connection string
  c.tracing.instrument :redis, describes: 'redis://127.0.0.1:6379/0', service_name: 'redis-connection-string'
  c.tracing.instrument :redis, describes: { url: 'redis://127.0.0.1:6379/1' }, service_name: 'redis-connection-url'
  # Network client hash
  c.tracing.instrument :redis, describes: { host: 'my-host.com', port: 6379, db: 1, scheme: 'redis' }, service_name: 'redis-connection-hash'
  # Only a subset of the connection hash
  c.tracing.instrument :redis, describes: { host: ENV['APP_CACHE_HOST'], port: ENV['APP_CACHE_PORT'] }, service_name: 'redis-cache'
  c.tracing.instrument :redis, describes: { host: ENV['SIDEKIQ_CACHE_HOST'] }, service_name: 'redis-sidekiq'
end

여러 describes 설정이 연결과 일치하면 마지막으로 설정된 일치 규칙이 적용돼요.

Resque

Resque 통합은 perform 메서드를 감싸는 Resque 훅을 사용해요.

Resque 작업에 추적을 추가하려면:

require 'resque'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :resque, **options
end

options는 다음 키워드 인자예요:

Key Description Default
error_handler 작업에서 오류가 발생했을 때 호출되는 사용자 지정 오류 처리기예요. span과 error를 인자로 받아요. 기본적으로 스팬에 오류를 설정해요. 일시적인 오류를 무시하는 데 유용해요. `proc {

Rest Client

rest-client 통합은 ddtrace 미들웨어를 통해 사용할 수 있어요:

require 'rest_client'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :rest_client, **options
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_REST_CLIENT_SERVICE_NAME rest_client 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 rest_client
peer_service DD_TRACE_REST_CLIENT_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
split_by_domain true로 설정하면 요청 도메인을 서비스 이름으로 사용해요. false

Roda

Roda 통합은 요청을 추적해요.

Roda 통합은 Datadog.configure로 활성화할 수 있어요. 분산 추적을 위해 이 통합을 use Datadog::Tracing::Contrib::Rack::TraceMiddleware를 통해 Rack과 함께 사용하는 걸 권장해요.

require "roda"
require "ddtrace"

class SampleApp < Roda
  use Datadog::Tracing::Contrib::Rack::TraceMiddleware

  Datadog.configure do |c|
    c.tracing.instrument :roda, **options
  end

  route do |r|
    r.root do
      r.get do
        'Hello World!'
      end
    end
  end
end

options는 다음 키워드 인자예요:

Key Description Default
service_name roda 계측의 서비스 이름이에요. 'nil'

RSpec

Net/HTTP

Net/HTTP 통합은 표준 라이브러리 Net::HTTP 모듈을 사용한 모든 HTTP 호출을 추적해요.

require 'net/http'
require 'ddtrace'

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'))

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_NET_HTTP_SERVICE_NAME net/http 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 net/http
peer_service DD_TRACE_NET_HTTP_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
distributed_tracing 분산 추적을 활성화해요 true
split_by_domain true로 설정하면 요청 도메인을 서비스 이름으로 사용해요. false
error_status_codes DD_TRACE_HTTP_ERROR_STATUS_CODES 오류로 추적해야 할 HTTP 상태 코드의 범위 또는 배열이에요. 400...600

각 연결 객체를 개별적으로 구성하고 싶다면 Datadog.configure_onto를 이렇게 사용할 수 있어요:

client = Net::HTTP.new(host, port)
Datadog.configure_onto(client, **options)

OpenSearch

OpenSearch 통합은 Client 객체에서 perform_request에 대한 모든 호출을 추적해요:

require 'opensearch'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :opensearch, **options
end

# Perform a query to OpenSearch
client = OpenSearch::Client.new(
  host: 'https://localhost:9200',
  user: 'user',
  password: 'password',
)
client.cluster.health

options는 다음 키워드 인자예요:

Key Env Var Description Default
service_name DD_TRACE_OPENSEARCH_SERVICE_NAME opensearch 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 opensearch
peer_service DD_TRACE_OPENSEARCH_PEER_SERVICE 애플리케이션이 연결하는 외부 서비스의 이름이에요 nil
quantize 양자화 옵션을 담은 해시예요. 양자화하지 않을 키의 :show Array(또는 양자화를 건너뛸 :all), 또는 완전히 제외할 키의 :exclude Array를 포함할 수 있어요. {}

Postgres

PG 통합은 pg gem을 통해 보내진 SQL 명령을 다음과 같이 추적해요:

  • exec, exec_params, exec_prepared;
  • async_exec, async_exec_params, async_exec_prepared; 또는,
  • sync_exec, sync_exec_params, sync_exec_prepared
require 'pg'
require 'ddtrace'

Datadog.configure do |c|
  c.tracing.instrument :pg, **options
end

options는 다음 키워드 인자예요:

Key Env Var Description Default
enabled Postgres를 추적할지 여부를 정의해요. true
service_name DD_TRACE_PG_SERVICE_NAME pg 계측을 실행하는 애플리케이션의 이름이에요. global_default_service_name으로 덮어쓸 수 있어요. 자세한 내용은 추가 설정을 참고해요 pg