All Products
Search
Document Center

Application Real-Time Monitoring Service:Use OpenTelemetry to report the trace data of Ruby applications

Last Updated:Jan 29, 2024

Before you can view the trace data of your application, you must use a client to report the trace data to Managed Service for OpenTelemetry. This topic describes how to use OpenTelemetry SDK for Ruby to report the trace data of a Ruby application.

Prerequisites

To obtain an endpoint of OpenTelemetry, perform the following steps:

  1. Log on to the Managed Service for OpenTelemetry console.

  2. In the left-side navigation pane, click Cluster Configurations. Then, click the Access point information tab.

  3. In the top navigation bar, select a region. In the Cluster Information section, turn on Show Token.

  4. In the Client section, click OpenTelemetry.

    Obtain an endpoint of OpenTelemetry in the Related Information column of the table in the lower part. OT接入点信息

    Note

    If your application is deployed in an Alibaba Cloud production environment, use a Virtual Private Cloud (VPC) endpoint. Otherwise, use a public endpoint.

Background information

  • OpenTelemetry supports the following Ruby versions: MRI Ruby 3.0 and later, JRuby 9.3.2.0 and later, and TruffleRuby 22.1 and later.

  • OpenTelemetry SDK for Ruby supports manual and semi-automatic instrumentation. Semi-automatic instrumentation means that you do not need to manually create spans, but you must add a configuration file. For more information about the frameworks supported by semi-automatic instrumentation, see OpenTelemetry official documentation.

Supported Ruby frameworks

  • action_pack

  • action_view

  • active_job

  • active_model_serializers

  • active_record

  • active_support

  • aws_sdk

  • bunny

  • concurrent_ruby

  • dalli

  • delayed_job

  • ethon

  • excon

  • faraday

  • grape

  • graphql

  • gruf

  • http

  • http_client

  • httpx

  • koala

  • lmdb

  • mongo

  • mysql2

  • net_http

  • pg

  • que

  • racecar

  • rack

  • rails

  • rake

  • rdkafka

  • redis

  • resque

  • restclient

  • rspec

  • ruby_kafka

  • sidekiq

  • sinatra

  • trilogy

Sample code

Download the sample code from ruby-opentelemetry-demo.

Method 1: Use the HTTP protocol to report data

  1. Install the following OpenTelemetry dependencies that are required for manual instrumentation:

    gem install opentelemetry-api
    gem install opentelemetry-sdk
    gem install opentelemetry-exporter-otlp
  2. Initialize OpenTelemetry.

    Add a component that is used to export monitoring data, and replace <endpoint> with the endpoint that you obtained.

    require 'opentelemetry/sdk'
    require 'opentelemetry-exporter-otlp'
    
    OpenTelemetry::SDK.configure do |c|
      c.add_span_processor(
        OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
          OpenTelemetry::Exporter::OTLP::Exporter.new(
            endpoint: '<endpoint>' # The endpoint of OpenTelemetry that is accessible over HTTP.
          )
        )
      )
      c.resource = OpenTelemetry::SDK::Resources::Resource.create({
        OpenTelemetry::SemanticConventions::Resource::SERVICE_NAMESPACE => 'tracing',
        OpenTelemetry::SemanticConventions::Resource::SERVICE_NAME => 'ruby_demo', # The name of the Ruby application whose data you want to report by using OpenTelemetry.
        OpenTelemetry::SemanticConventions::Resource::SERVICE_VERSION => '0.0.1',
      })
    end
  3. Obtain a tracer and create a span.

    tracer = OpenTelemetry.tracer_provider.tracer('<your_tracer_name>', '0.1.0')
    
    tracer.in_span('parent_span') do |parent_span|
      # ...
    end
  4. Obtain the current span, add information to the current span, and then obtain the trace ID and span ID.

    # ...
    tracer.in_span('parent_span') do |parent_span|
      # The current span is a parent span named parent_span.
      current_span = OpenTelemetry::Trace::current_span
      current_span.set_attribute('key', 'value')
      pp current_span.context.trace_id
      pp current_span.context.span_id
    end
  5. Create a nested span.

    # ...
    tracer.in_span('parent_span') do |parent_span|
      # ...
      tracer.in_span('child_span') do |child_span|
        # In this case, the current span is a child span named child_span.
        current_span = OpenTelemetry::Trace::current_span
        pp current_span
      end
    end

    View the complete sample code

    require 'opentelemetry/sdk'
    require 'opentelemetry-exporter-otlp'
    
    OpenTelemetry::SDK.configure do |c|
      c.add_span_processor(
        OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
          OpenTelemetry::Exporter::OTLP::Exporter.new(
            endpoint: '<endpoint>' # The endpoint of OpenTelemetry that is accessible over HTTP.
          )
        )
      )
      c.resource = OpenTelemetry::SDK::Resources::Resource.create({
        OpenTelemetry::SemanticConventions::Resource::SERVICE_NAMESPACE => 'tracing',
        OpenTelemetry::SemanticConventions::Resource::SERVICE_NAME => 'ruby_demo', # The name of the Ruby application whose data you want to report by using OpenTelemetry.
        OpenTelemetry::SemanticConventions::Resource::SERVICE_VERSION => '0.0.1',
      })
    
      # Set the application name without using the OpenTelemetry Resources API.
      # c.service_name = 'ruby_demo'
    end
    
    tracer = OpenTelemetry.tracer_provider.tracer('instrumentation_library_name', '0.1.0')
    
    tracer.in_span('parent_span') do |parent_span|
      # Configure the attributes of the span.
      parent_span.set_attribute('language', 'ruby')
      parent_span.set_attribute("attribute_key", ["attribute_value1", "attribute_value1", "attribute_value1"])
      # Add an event to the span.
      parent_span.add_event("event", attributes: {
        "pid" => 1234,
        "signal" => "SIGHUP"
      })
    
      # Obtain the trace ID and the ID of the current span.
      current_span = OpenTelemetry::Trace::current_span
      pp current_span.context.trace_id
      pp current_span.context.span_id
    
      tracer.in_span('child_span') do |child_span|
        child_span.add_attributes({
          "key1" => "value1",
          "key2" => "value2"
        })
    
        child_span.add_event("mock exception here")
    
        begin
          raise 'An error has occurred'
        rescue
          # Set the state of child_span to error if an exception occurs.
          child_span.status = OpenTelemetry::Trace::Status.error("error in child span")
        end
    
        pp child_span
    
      end
    end
    
    sleep 10
  6. Run the application.

    ruby manual.rb

Method 2: Automatically report data

OpenTelemetry SDK for Ruby also allows you to implement automatic instrumentation and observation for your application. This section describes how to use OpenTelemetry to implement automatic tracing analysis on a Rails application and report the trace data of the application.

  1. Download the open source web application framework Rails.

    gem install rails
  2. Use Rails to create a web project.

    rails new <your-project-name>
    • Replace <your-project-name> with the name of your application. Example: rails new auto-demo.

    • If the Rails is not currently installed on this system error message is returned after you run the preceding command, close and reopen the CLI, and then enter and run the command again.

  3. Add the following content to the Gemfile in the directory of the application:

    gem 'opentelemetry-sdk'
    gem 'opentelemetry-exporter-otlp'
    gem 'opentelemetry-instrumentation-all'
  4. Download the third-party dependencies required by the application.

    1. Go to the root directory of the project.

      cd <your-project-name>
    2. Download the Ruby dependency management tool Bundler.

      gem install bundler
    3. Download the dependencies in the Gemfile.

      bundle install
  5. In the <your-project-name>/config/initializers directory, create a opentelemetry.rb file and add the following content to the file:

    # config/initializers/opentelemetry.rb
    require 'opentelemetry/sdk'
    require 'opentelemetry/exporter/otlp'
    require 'opentelemetry/instrumentation/all'
    
    OpenTelemetry::SDK.configure do |c|
      c.add_span_processor(
        OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
          OpenTelemetry::Exporter::OTLP::Exporter.new(
            endpoint: '<endpoint>' # The endpoint of OpenTelemetry that is accessible over HTTP.
          )
        )
      )
      c.resource = OpenTelemetry::SDK::Resources::Resource.create({
        OpenTelemetry::SemanticConventions::Resource::HOST_NAME => '<your-host-name>', # The hostname.
      })
      c.service_name = '<your-service-name>'    # The name of the application.
      c.use_all()    # The libraries supported by automatic OpenTelemetry observation. 
    end
    • Replace <endpoint> with the endpoint that you obtained.

    • Replace <your-host-name> and <your-service-name> with the actual hostname and application name.

  6. Run the project.

    rails server

    If the following results are returned, the operation is successful:

    * Puma version: 5.6.5 (ruby 2.7.2-p137) ("Birdie's Version")
    *  Min threads: 5
    *  Max threads: 5
    *  Environment: development
    *          PID: 79842
    * Listening on http://127.0.0.1:3000
    * Listening on http://[::1]:3000
    Use Ctrl-C to stop
  7. Visit http://127.0.0.1:3000 in a browser. If the following content is displayed on the CLI, the data is reported to the Managed Service for OpenTelemetry console.

    Started GET "/" for 127.0.0.1 at 2023-01-01 10:00:00 +0800
    Processing by Rails::WelcomeController#index as HTML
      Rendering /Users/username/.rvm/gems/ruby-2.7.2/gems/railties-7.0.4.3/lib/rails/templates/rails/welcome/index.html.erb
      Rendered /Users/username/.rvm/gems/ruby-2.7.2/gems/railties-7.0.4.3/lib/rails/templates/rails/welcome/index.html.erb (Duration: 0.8ms | Allocations: 665)
    Completed 200 OK in 6ms (Views: 2.1ms | ActiveRecord: 0.0ms | Allocations: 5440)

View the monitoring data

Log on to the ARMS console. In the left-side navigation pane, choose Application Monitoring > Applications. On the Applications page, click the name of the application. On the page that appears, view the trace data.

Note

If the Java图标 icon is displayed in the Language column, the application is connected to Application Monitoring. If a hyphen (-) is displayed, the application is connected to Managed Service for OpenTelemetry.