Docs Menu
Docs Home
/ /

Trace with OpenTelemetry

In this guide, you will learn how to use OpenTelemetry tracing with the Ruby driver. OpenTelemetry is an open source observability framework that provides a standardized way to instrument, generate, collect, and export telemetry data.

The Ruby driver supports OpenTelemetry tracing to help you understand the performance and behavior of your MongoDB operations. When you enable tracing, the driver creates spans that represent operations such as queries, updates, and transactions. These spans include attributes that follow MongoDB semantic conventions.

To use OpenTelemetry tracing, you must install the OpenTelemetry Ruby SDK and an exporter. To install these in your application, add the following gems to your Gemfile:

gem 'opentelemetry-sdk'
gem 'opentelemetry-exporter-otlp' # or your preferred exporter

If you enable tracing but the OpenTelemetry library is not loaded, the driver logs a warning and automatically disables tracing.

You can enable OpenTelemetry tracing by specifying the tracing option when you create a client, or by setting an environment variable.

Note

If you don't set tracing in the client configuration or by using the environment variable, tracing is disabled by default.

To enable tracing when you create a client, pass the tracing option with enabled set to true, as shown in the following example:

client = Mongo::Client.new(['localhost:27017'],
database: 'my_database',
tracing: {
enabled: true
}
)

To enable tracing by using an environment variable, set the OTEL_RUBY_INSTRUMENTATION_MONGODB_ENABLED environment variable before you create a client, as shown in the following example:

export OTEL_RUBY_INSTRUMENTATION_MONGODB_ENABLED=true

You can use any of the following values in the environment variable to enable tracing:

  • true

  • 1

  • yes

After you set the variable, create your client, as shown in the following example:

client = Mongo::Client.new(['localhost:27017'],
database: 'my_database')

The tracing option accepts the following parameters:

Parameter
Type
Description

:enabled

Boolean

Enables or disables OpenTelemetry tracing.

Default: nil

:query_text_max_length

Integer

Specifies the maximum length of query text to
include in span attributes. Set to 0 to exclude
query text. The query text appears in the
db.query.text attribute.

Default: nil

:tracer

OpenTelemetry::Trace::Tracer

Specifies a custom OpenTelemetry tracer instance.

Default: Uses the default tracer from the
global tracer provider

The following example shows how to configure all available tracing options:

client = Mongo::Client.new(['localhost:27017'],
database: 'my_database',
tracing: {
enabled: true,
query_text_max_length: 1024,
tracer: my_custom_tracer
}
)

The Ruby driver creates OpenTelemetry spans for both high-level operations and low-level commands. The following sections describe the spans created and the attributes included.

High-level operations are the methods you call directly on collections and databases. The driver creates spans for the following operations:

Operation Type
Operations

Collection operations

find, insert_one, insert_many, update_one, update_many, delete_one, delete_many, find_one_and_update, find_one_and_delete, find_one_and_replace, replace_one, count_documents, estimated_document_count, distinct, aggregate

Index operations

create_index, create_indexes, drop_index, drop_all_indexes, list_indexes

Database operations

list_collections, create_collection, drop_collection, list_databases

Span names for high-level operations use the format {operation_name}.{collection_name}. For example, find.users, insertOne.orders, or aggregate.products.

Low-level commands are the actual commands sent to the MongoDB server over the wire protocol. The following lists some examples of low-level commands for which the driver creates spans:

  • find

  • insert

  • update

  • delete

  • aggregate

  • create

  • drop

Span names for low-level commands use the format {command_name}. For example, find, insert, or update.

Command spans are nested under their corresponding operation spans.

The driver follows MongoDB semantic conventions and includes span attributes that provide context about each operation.

All spans include the following attributes:

  • db.system: Always set to mongodb

  • db.namespace: The database name

  • db.collection.name: The collection name (when applicable)

  • db.command.name: The MongoDB command name (command spans only)

  • db.query.summary: A high-level summary of the query structure

Command spans include the following network attributes:

  • server.address: MongoDB server host

  • server.port: MongoDB server port

  • network.transport: Transport protocol such as tcp

Command spans include the following connection attributes:

  • db.mongodb.server_connection_id: Server-assigned connection ID

  • db.mongodb.driver_connection_id: Driver-assigned connection ID

When you use sessions or transactions, spans include the following attributes:

  • db.mongodb.lsid: Logical session ID (when using sessions)

  • db.mongodb.txn_number: Transaction number (when in a transaction)

  • db.mongodb.cursor_id: Cursor ID (for operations that return cursors)

When you configure query_text_max_length with a value greater than 0, spans include the following attribute:

  • db.query.text: The full query text, truncated to the specified maximum length

When operations fail, the driver records exception details with OpenTelemetry's exception recording mechanism and sets the span status to ERROR. For MongoDB operation failures, the db.response.status_code attribute contains the error code.

The driver creates a special transaction span that encompasses all operations within an explicit transaction. The following example demonstrates transaction tracing:

session = client.start_session
session.with_transaction do
collection.insert_one({ name: 'Alice' }, session: session)
collection.update_one(
{ name: 'Bob' },
{ '$set' => { age: 30 } },
session: session
)
end

The preceding example produces a span hierarchy similar to the following structure:

transaction
└── insertOne.users
└── insert (command)
└── updateOne.users
└── update (command)

Note

Implicit sessions do not create transaction spans.

When operations fail, the driver records exceptions in the span by using OpenTelemetry's exception recording mechanism. The span status is then set to ERROR.

For MongoDB operation failures, the db.response.status_code attribute contains the error code.

Errors do not prevent the driver from raising the exception to your application.

Consider the following performance implications when you use OpenTelemetry tracing:

  • When you enable tracing, the driver incurs minimal overhead for span creation and attribute collection.

  • Query text capture (db.query.text) has additional overhead and you should use it judiciously in production. Setting query_text_max_length to 0 disables query text capture for better performance.

  • When you disable tracing, there is no performance impact because the feature is completely bypassed.

The following example shows how to set up OpenTelemetry tracing for a MongoDB application:

require 'mongo'
require 'opentelemetry/sdk'
# Configure OpenTelemetry
OpenTelemetry::SDK.configure do |c|
c.service_name = 'my-app'
end
# Create MongoDB client with tracing enabled
client = Mongo::Client.new(['localhost:27017'],
database: 'test',
tracing: {
enabled: true,
query_text_max_length: 1024
}
)
# Use the client normally - operations are traced
collection = client[:users]
collection.insert_one({ name: 'Alice', age: 30 })
collection.find({ age: { '$gte': 25 } }).to_a

To learn more about OpenTelemetry tracing with Ruby, see the OpenTelemetry Ruby SDK.

Back

Change Streams

On this page