Reference documentation and code samples for the Cloud Trace API class Google::Cloud::Trace::Middleware.
Trace Middleware
A Rack middleware that manages trace context and captures a trace of
the request. Specifically, it:
Reads the trace context from the request headers, if present.
Otherwise, generates a new trace context.
Makes a sampling decision if one is not already specified.
Records a span measuring the entire handling of the request,
annotated with a set of standard request data.
Makes the trace context available so downstream middlewares and the
app can add further spans to the trace.
Sends the completed trace to the Stackdriver service.
Installing
To use this middleware, simply install it in your middleware stack.
Here is an example Sinatra application that includes the Trace
middleware:
```ruby
Simple sinatra application
require "sinatra"
require "google/cloud/trace"
use Google::Cloud::Trace::Middleware
get "/" do
"Hello World!"
end
```
Here is an example config.ru file for a web application that uses
the standard Rack configuration mechanism.
```ruby
config.ru for simple Rack application
require "google/cloud/trace"
use Google::Cloud::Trace::Middleware
run MyApp
```
If your application uses Ruby On Rails, you may also use the provided
Railtie for close integration with Rails and
ActiveRecord.
Custom measurements
By default, this middleware creates traces that measure just the http
request handling as a whole. If you want to provide more detailed
measurements of smaller processes, use the classes provided in this
library. Below is a Sinatra example to get you started.
```ruby
Simple sinatra application
require "sinatra"
require "google/cloud/trace"
use Google::Cloud::Trace::Middleware
get "/" do
Google::Cloud::Trace.in_span "Sleeping on the job!" do
sleep rand
end
"Hello World!"
end
```
Error handling
An error encountered during the reporting of traces by the middleware
can be handled using a Proc set in the on_error configuration. (See
configure.) The Proc must take the error object
as the single argument.
Google::Cloud::Trace.configure do |config|
config.on_error = lambda do |error|
Google::Cloud::ErrorReporting.report error
end
end
use Google::Cloud::Trace::Middleware
get "/" do
Google::Cloud::Trace.in_span "Sleeping on the job!" do
sleep rand
end
"Hello World!"
end
```
Sampling and blacklisting
A sampler makes the decision whether to record a trace for each
request (if the decision was not made by the context, e.g. by providing
a request header). By default, this sampler is the default
TimeSampler, which enforces a maximum QPS per
process, and blacklists a small number of request paths such as
health checks sent by Google App Engine. You may adjust this behavior
by providing an alternate sampler. See
TimeSampler.
Inherits
Object
Methods
#call
defcall(env)->Rack::Response
Implementation of the trace middleware. Creates a trace for this
request, populates it with a root span for the entire request, and
ensures it is reported back to Stackdriver.
Parameter
env (Hash) — Rack environment hash
Returns
(Rack::Response) — The response from downstream Rack app
service (Google::Cloud::Trace::Service, AsyncReporter) (defaults to: nil) — The service object to update traces. Optional if running on GCE.
kwargs (Hash) — Hash of configuration settings. Used for backward
API compatibility. See the Instrumentation Guide and Configuration
Guide
for the prefered way to set configuration parameters.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,["# Cloud Trace API - Class Google::Cloud::Trace::Middleware (v0.45.0)\n\nVersion latestkeyboard_arrow_down\n\n- [0.45.0 (latest)](/ruby/docs/reference/google-cloud-trace/latest/Google-Cloud-Trace-Middleware)\n- [0.44.1](/ruby/docs/reference/google-cloud-trace/0.44.1/Google-Cloud-Trace-Middleware)\n- [0.43.0](/ruby/docs/reference/google-cloud-trace/0.43.0/Google-Cloud-Trace-Middleware)\n- [0.42.2](/ruby/docs/reference/google-cloud-trace/0.42.2/Google-Cloud-Trace-Middleware)\n- [0.41.4](/ruby/docs/reference/google-cloud-trace/0.41.4/Google-Cloud-Trace-Middleware) \nReference documentation and code samples for the Cloud Trace API class Google::Cloud::Trace::Middleware.\n\nTrace Middleware\n----------------\n\nA Rack middleware that manages trace context and captures a trace of\nthe request. Specifically, it:\n\n\u003cbr /\u003e\n\n- Reads the trace context from the request headers, if present. Otherwise, generates a new trace context.\n- Makes a sampling decision if one is not already specified.\n- Records a span measuring the entire handling of the request, annotated with a set of standard request data.\n- Makes the trace context available so downstream middlewares and the app can add further spans to the trace.\n- Sends the completed trace to the Stackdriver service.\n\n### Installing\n\n\u003cbr /\u003e\n\nTo use this middleware, simply install it in your middleware stack.\nHere is an example Sinatra application that includes the Trace\nmiddleware:\n\n\\`\\`\\`ruby\n\nSimple sinatra application\n--------------------------\n\nrequire \"sinatra\"\nrequire \"google/cloud/trace\"\n\nuse Google::Cloud::Trace::Middleware\n\nget \"/\" do\n\"Hello World!\"\nend\n\\`\\`\\`\n\nHere is an example `config.ru` file for a web application that uses\nthe standard Rack configuration mechanism.\n\n\\`\\`\\`ruby\n\nconfig.ru for simple Rack application\n-------------------------------------\n\nrequire \"google/cloud/trace\"\nuse Google::Cloud::Trace::Middleware\n\nrun MyApp\n\\`\\`\\`\n\nIf your application uses Ruby On Rails, you may also use the provided\n[Railtie](/ruby/docs/reference/google-cloud-trace/latest/Google-Cloud-Trace-Railtie \"Google::Cloud::Trace::Railtie (class)\") for close integration with Rails and\nActiveRecord.\n\n### Custom measurements\n\nBy default, this middleware creates traces that measure just the http\nrequest handling as a whole. If you want to provide more detailed\nmeasurements of smaller processes, use the classes provided in this\nlibrary. Below is a Sinatra example to get you started.\n\n\\`\\`\\`ruby\n\nSimple sinatra application\n--------------------------\n\nrequire \"sinatra\"\nrequire \"google/cloud/trace\"\n\nuse Google::Cloud::Trace::Middleware\n\nget \"/\" do\nGoogle::Cloud::Trace.in_span \"Sleeping on the job!\" do\nsleep rand\nend\n\"Hello World!\"\nend\n\\`\\`\\`\n\n### Error handling\n\nAn error encountered during the reporting of traces by the middleware\ncan be handled using a Proc set in the `on_error` configuration. (See\n[configure](/ruby/docs/reference/google-cloud-trace/latest/Google-Cloud-Trace#Google__Cloud__Trace_configure_class_ \"Google::Cloud::Trace.configure (method)\").) The Proc must take the error object\nas the single argument.\n\n\\`\\`\\`ruby\n\nConfigure error handling\n------------------------\n\nrequire \"sinatra\"\nrequire \"google/cloud/trace\"\nrequire \"google/cloud/error_reporting\"\n\nGoogle::Cloud::Trace.configure do \\|config\\|\nconfig.on_error = lambda do \\|error\\|\nGoogle::Cloud::ErrorReporting.report error\nend\nend\n\nuse Google::Cloud::Trace::Middleware\n\nget \"/\" do\nGoogle::Cloud::Trace.in_span \"Sleeping on the job!\" do\nsleep rand\nend\n\"Hello World!\"\nend\n\\`\\`\\`\n\n### Sampling and blacklisting\n\nA sampler makes the decision whether to record a trace for each\nrequest (if the decision was not made by the context, e.g. by providing\na request header). By default, this sampler is the default\n[TimeSampler](/ruby/docs/reference/google-cloud-trace/latest/Google-Cloud-Trace-TimeSampler \"Google::Cloud::Trace::TimeSampler (class)\"), which enforces a maximum QPS per\nprocess, and blacklists a small number of request paths such as\nhealth checks sent by Google App Engine. You may adjust this behavior\nby providing an alternate sampler. See\n[TimeSampler](/ruby/docs/reference/google-cloud-trace/latest/Google-Cloud-Trace-TimeSampler \"Google::Cloud::Trace::TimeSampler (class)\"). \n\nInherits\n--------\n\n- Object\n\nMethods\n-------\n\n### #call\n\n def call(env) -\u003e Rack::Response\n\nImplementation of the trace middleware. Creates a trace for this\nrequest, populates it with a root span for the entire request, and\nensures it is reported back to Stackdriver. \n**Parameter**\n\n- **env** (Hash) --- Rack environment hash \n**Returns**\n\n- (Rack::Response) --- The response from downstream Rack app\n\n### #initialize\n\n def initialize(app, service: nil, **kwargs) -\u003e Middleware\n\nCreate a new Middleware for traces \n**Parameters**\n\n- **app** (Rack Application) --- Rack application\n- **service** (Google::Cloud::Trace::Service, AsyncReporter) *(defaults to: nil)* --- The service object to update traces. Optional if running on GCE.\n- **kwargs** (Hash) --- Hash of configuration settings. Used for backward API compatibility. See the [Instrumentation Guide](./INSTRUMENTATION \"Instrumentation Guide\") and [Configuration\nGuide](https://googleapis.dev/ruby/stackdriver/latest/file.INSTRUMENTATION_CONFIGURATION.html) for the prefered way to set configuration parameters. \n**Returns**\n\n- ([Middleware](./Google-Cloud-Trace-Middleware)) --- a new instance of Middleware\n\nConstants\n---------\n\n### AGENT_NAME\n\n**value:** \"ruby #[VERSION](/ruby/docs/reference/google-cloud-trace/latest/Google-Cloud-Trace#Google__Cloud__Trace__VERSION \"Google::Cloud::Trace::VERSION (constant)\")\".freeze \nThe name of this trace agent as reported to the Stackdriver backend."]]