This example application demonstrates how to use OpenCensus to record traces for a Sinatra-based web application. You can find the source code for the application at https://github.com/census-instrumentation/opencensus-ruby/tree/master/examples/hello-world.
Ruby 2.2 or later is required. Make sure you have Bundler installed as well.
gem install bundler
Get the example from the OpenCensus Ruby repository on Github, and cd into the example application directory.
git clone https://github.com/census-instrumentation/opencensus-ruby.git
Install the dependencies using Bundler.
Run the application locally on your workstation with:
bundle exec ruby hello.rb
This will run on port 4567 by default, and display application logs on the terminal. From a separate shell, you can send requests using a tool such as curl:
The running application will log the captured traces.
The example application’s Gemfile includes the `opencensus` gem:
gem "faraday", "~> 0.14"
gem "opencensus", "~> 0.3"
gem "sinatra", "~> 2.0"
Following is the `hello.rb` source file from the example:
# Install the Rack middleware to trace incoming requests.
# Access the Faraday middleware which will be used to trace outgoing
# HTTP requests.
# Each request will be traced automatically by the middleware.
get "/" do
# Traces for this request will also include sub-spans as indicated
get "/lengthy" do
# Configure this Faraday connection with a middleware to trace
# outgoing requests.
conn = Faraday.new(url: "http://www.google.com") do |c|
# You may instrument your code to create custom spans for
# long-running operations.
OpenCensus::Trace.in_span "long task" do
The OpenCensus Ruby API is documented at: http://www.rubydoc.info/gems/opencensus