Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# solarwinds_apm Examples

Quick-start examples demonstrating tracing, metrics, logs, and custom instrumentation with the `solarwinds_apm` gem.

> **⚠️ Warning: Gem Installation**
> Each example uses `bundler/inline`, which will **automatically download and install `solarwinds_apm` and all its OpenTelemetry dependencies** (`opentelemetry-ruby`, `opentelemetry-ruby-contrib`, etc.) into your system Ruby gem directory on the first run.
> If you do not want to modify your local gem environment, run the examples inside an isolated environment such as a Docker container or a dedicated rbenv/rvm gemset.

## Prerequisites

- **Ruby >= 3.1.0**
- **Bundler** (`gem install bundler`)
- **SolarWinds Observability service key** — obtain one from [SolarWinds Observability](https://support.solarwinds.com/observability)

Set the required environment variable before running any example:

```bash
export SW_APM_SERVICE_KEY=<your-api-token>:<your-service-name>
```

The format is `token:service_name` where `service_name` is how your application appears in SolarWinds Observability.

## Examples

| File | Description |
|------|-------------|
| [traces_example.rb](traces_example.rb) | Create custom trace spans using both the SolarWindsAPM convenience API and the standard OpenTelemetry API. Demonstrates nested spans, trace context, and custom transaction names. |
| [metrics_example.rb](metrics_example.rb) | Record custom metrics (counters, up-down counters, histograms) using the OpenTelemetry Metrics API with the MeterProvider configured by `solarwinds_apm`. |
| [logs_example.rb](logs_example.rb) | Emit structured log records using the OpenTelemetry Logs API, correlated with the current trace context. |
| [custom_instrumentation_example.rb](custom_instrumentation_example.rb) | Use `add_tracer` to automatically wrap existing instance and class methods with trace spans — no manual span creation needed. |

## Running the Examples

Each example is self-contained and uses `bundler/inline` to resolve dependencies, so no separate `bundle install` is needed.

### Traces

```bash
ruby traces_example.rb
```

### Metrics

The export interval is set to 2 seconds (`OTEL_METRIC_EXPORT_INTERVAL=2000`) so results appear quickly. The default is 60 seconds.

```bash
OTEL_METRIC_EXPORT_INTERVAL=2000 OTEL_METRICS_EXPORTER=otlp ruby metrics_example.rb
```

### Logs

```bash
OTEL_RUBY_INSTRUMENTATION_LOGGER_ENABLED=true ruby logs_example.rb
```

### Custom Instrumentation

```bash
ruby custom_instrumentation_example.rb
```

## Console Output for Development

To see exported data printed to the console (useful during local development), use the `console` exporter for the relevant signal:

```bash
# Traces
OTEL_TRACES_EXPORTER=console ruby traces_example.rb

# Metrics
OTEL_METRICS_EXPORTER=console OTEL_METRIC_EXPORT_INTERVAL=2000 ruby metrics_example.rb

# Logs
OTEL_LOGS_EXPORTER=console OTEL_RUBY_INSTRUMENTATION_LOGGER_ENABLED=true ruby logs_example.rb

# Custom Instrumentation
OTEL_TRACES_EXPORTER=console ruby custom_instrumentation_example.rb
```

## Configuration

See [CONFIGURATION.md](../CONFIGURATION.md) for the full configuration reference, including:

- Debug logging (`SW_APM_DEBUG_LEVEL`)
- Collector endpoint override (`SW_APM_COLLECTOR`)
- Transaction filtering
- SQL query tagging
- Programmatic instrumentation configuration

## Validating Results in SolarWinds Observability

After running an example, sign in to [SolarWinds Observability](https://my.na-01.cloud.solarwinds.com/) and navigate as follows:

### Verify Traces and Custom Instrumentation

**APM → \<your-service-name\> → Traces**

Spans created by `traces_example.rb` and `custom_instrumentation_example.rb` appear here within a few seconds of the script completing.

### Verify Logs

**Logs → search** `program:"<your-service-name>"`

Log records emitted by `logs_example.rb` appear here.

### Verify Metrics

**APM → \<your-service-name\> → Metrics**

Metrics recorded by `metrics_example.rb` (e.g. `app.requests`, `app.active_connections`, `app.request.duration`) appear here. Set `OTEL_METRIC_EXPORT_INTERVAL=2000` to reduce the wait to ~2 seconds instead of the default 60.

## Additional Resources

- [SolarWinds APM Ruby README](../README.md)
- [OpenTelemetry Ruby Documentation](https://opentelemetry.io/docs/instrumentation/ruby/)
- [SolarWinds Observability Documentation](https://documentation.solarwinds.com/en/success_center/observability/default.htm)
95 changes: 95 additions & 0 deletions examples/custom_instrumentation_example.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# frozen_string_literal: true

# © 2026 SolarWinds Worldwide, LLC. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at:http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

# This example demonstrates the SolarWindsAPM::API::Tracer module, which provides
# the `add_tracer` method for automatically wrapping existing methods with trace spans.
#
# Usage:
# SW_APM_SERVICE_KEY=<your-token>:my-service ruby custom_instrumentation_example.rb
#
# For console output during development, set:
# OTEL_TRACES_EXPORTER=console

require 'bundler/inline'

gemfile(true) do
source 'https://rubygems.org'
gem 'solarwinds_apm', path: File.expand_path('..', __dir__)
end

puts '--- solarwinds_apm Custom Instrumentation Example ---'
puts

# Wait for the HttpSampler to receive tracing settings from the SolarWinds collector.
# solarwinds_apm replaces the default OTel sampler with a custom HttpSampler that fetches
# settings over HTTP on startup. Until settings arrive, all spans are dropped. This call
# blocks until the sampler is ready (or the timeout elapses).
warn '[solarwinds_apm] Not ready after 10 seconds — spans may not be sampled.' unless SolarWindsAPM::API.solarwinds_ready?(10_000)

# --- Using add_tracer to instrument instance methods ---
# Include SolarWindsAPM::API::Tracer and use add_tracer to automatically
# wrap method calls in a trace span.

class OrderProcessor
include SolarWindsAPM::API::Tracer

def process(order_id)
puts " Processing order #{order_id}..."
validate(order_id)
charge(order_id)
puts " Order #{order_id} processed."
end

def validate(order_id)
sleep(0.02)
puts " Validated order #{order_id}"
end

def charge(order_id)
sleep(0.03)
puts " Charged order #{order_id}"
end

# Instrument methods with custom span names
add_tracer :process, 'order.process'
add_tracer :validate, 'order.validate'
add_tracer :charge, 'order.charge', kind: :internal
end

# --- Using add_tracer to instrument class methods ---

class NotificationService
def self.send_email(to)
sleep(0.01)
puts " Email sent to #{to}"
end

class << self
include SolarWindsAPM::API::Tracer

add_tracer :send_email, 'notification.send_email'
end
end

# --- Run the instrumented code ---

processor = OrderProcessor.new

puts 'Processing orders with automatic span instrumentation:'
processor.process('ORD-1001')
puts

processor.process('ORD-1002')
puts

puts 'Sending notification with instrumented class method:'
NotificationService.send_email('customer@example.com')

puts
puts '--- Custom instrumentation example complete ---'
sleep 5 # Ensure spans are exported before the process exits
75 changes: 75 additions & 0 deletions examples/logs_example.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# frozen_string_literal: true

# © 2026 SolarWinds Worldwide, LLC. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at:http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

# This example demonstrates how to emit structured logs using the OpenTelemetry Logs API
# with solarwinds_apm. Log records are correlated with the current trace context and
# exported via the OTLP logs exporter configured by the gem.
#
# Usage:
# OTEL_RUBY_INSTRUMENTATION_LOGGER_ENABLED=true \
# SW_APM_SERVICE_KEY=<your-token>:my-service ruby logs_example.rb
#
# For console output during development, set:
# OTEL_LOGS_EXPORTER=console

require 'bundler/inline'

gemfile(true) do
source 'https://rubygems.org'
gem 'solarwinds_apm', path: File.expand_path('..', __dir__)
end

puts '--- solarwinds_apm Logs Example ---'
puts

# --- Using the OpenTelemetry Logs API directly ---
# Access a Logger from the LoggerProvider configured by solarwinds_apm.

otel_logger = OpenTelemetry.logger_provider.logger(name: 'logs-example', version: '0.1.0')

# Emit log records within a trace span for correlation
tracer = OpenTelemetry.tracer_provider.tracer(ENV.fetch('OTEL_SERVICE_NAME', 'logs-example'))

tracer.in_span('example.logs_demo') do |_span|
# Emit an INFO log record
otel_logger.on_emit(
timestamp: Time.now,
severity_text: 'INFO',
body: 'Application started successfully',
attributes: { 'component' => 'startup', 'environment' => 'demo' }
)
puts 'Emitted INFO log: Application started successfully'

# Emit a WARN log record
otel_logger.on_emit(
timestamp: Time.now,
severity_text: 'WARN',
body: 'Cache miss for key: user_preferences',
attributes: { 'component' => 'cache', 'cache.key' => 'user_preferences' }
)
puts 'Emitted WARN log: Cache miss for key: user_preferences'

# Show trace context available for log correlation
trace_info = SolarWindsAPM::API.current_trace_info
puts
puts "Log records are correlated with trace_id: #{trace_info.trace_id}"
end

# Emit a log record outside of a span
otel_logger.on_emit(
timestamp: Time.now,
severity_text: 'DEBUG',
body: 'Cleanup task completed',
attributes: { 'component' => 'maintenance' }
)
puts 'Emitted DEBUG log (outside span): Cleanup task completed'

puts
puts 'Log records are exported via the OTLP logs exporter.'
puts '--- Logs example complete ---'
sleep 5 # Ensure logs are exported before the process exits
78 changes: 78 additions & 0 deletions examples/metrics_example.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# frozen_string_literal: true

# © 2026 SolarWinds Worldwide, LLC. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at:http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

# This example demonstrates how to create and record custom metrics using solarwinds_apm.
# solarwinds_apm initializes a global MeterProvider so your application can create
# Meters and Instruments using the standard OpenTelemetry Metrics API.
#
# Usage:
# OTEL_METRIC_EXPORT_INTERVAL=2000 SW_APM_SERVICE_KEY=<your-token>:my-service ruby metrics_example.rb
#
# For console output during development, set:
# OTEL_METRICS_EXPORTER=console

require 'bundler/inline'

gemfile(true) do
source 'https://rubygems.org'
gem 'solarwinds_apm', path: File.expand_path('..', __dir__)
end

puts '--- solarwinds_apm Metrics Example ---'
puts

# Acquire a Meter from the globally-configured MeterProvider
meter = OpenTelemetry.meter_provider.meter('metrics-example')

# --- Counter ---
# Counts the number of times an event occurs.

request_counter = meter.create_counter(
'app.requests',
description: 'Total number of requests processed',
unit: '{request}'
)

5.times do |i|
request_counter.add(1, attributes: { 'http.method' => 'GET', 'http.route' => '/api/users' })
puts "Recorded request #{i + 1}"
end

# --- UpDownCounter ---
# Tracks a value that can increase or decrease, such as active connections.

active_connections = meter.create_up_down_counter(
'app.active_connections',
description: 'Number of active connections',
unit: '{connection}'
)

3.times { active_connections.add(1, attributes: { 'server.region' => 'us-east-1' }) }
puts 'Opened 3 connections'

active_connections.add(-1, attributes: { 'server.region' => 'us-east-1' })
puts 'Closed 1 connection (2 remaining)'

# --- Histogram ---
# Records a distribution of values, such as request duration.

duration_histogram = meter.create_histogram(
'app.request.duration',
description: 'Request duration distribution',
unit: 'ms'
)

[12.5, 45.3, 8.1, 102.7, 23.4].each do |duration|
duration_histogram.record(duration, attributes: { 'http.method' => 'GET', 'http.status_code' => 200 })
puts "Recorded request duration: #{duration}ms"
end

puts
puts 'Metrics are aggregated and exported every 2 seconds by the configured exporter.'
puts '--- Metrics example complete ---'
sleep 5 # Ensure metrics are exported before the process exits
Loading
Loading