diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..0f64d8e --- /dev/null +++ b/examples/README.md @@ -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=: +``` + +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 → \ → 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:""` + +Log records emitted by `logs_example.rb` appear here. + +### Verify Metrics + +**APM → \ → 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) diff --git a/examples/custom_instrumentation_example.rb b/examples/custom_instrumentation_example.rb new file mode 100644 index 0000000..0635717 --- /dev/null +++ b/examples/custom_instrumentation_example.rb @@ -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=: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 diff --git a/examples/logs_example.rb b/examples/logs_example.rb new file mode 100644 index 0000000..73750f1 --- /dev/null +++ b/examples/logs_example.rb @@ -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=: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 diff --git a/examples/metrics_example.rb b/examples/metrics_example.rb new file mode 100644 index 0000000..e9e16b1 --- /dev/null +++ b/examples/metrics_example.rb @@ -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=: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 diff --git a/examples/traces_example.rb b/examples/traces_example.rb new file mode 100644 index 0000000..62d3767 --- /dev/null +++ b/examples/traces_example.rb @@ -0,0 +1,46 @@ +# 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 custom trace spans using solarwinds_apm. +# It shows both the standard OpenTelemetry API and the SolarWindsAPM convenience API. +# +# Usage: +# SW_APM_SERVICE_KEY=:my-service ruby traces_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 Traces Example ---' +puts "Service: #{ENV.fetch('OTEL_SERVICE_NAME', '(auto-detected from SW_APM_SERVICE_KEY)')}" +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 the SolarWindsAPM convenience API --- +# SolarWindsAPM::API.in_span acquires the correct Tracer automatically. + +SolarWindsAPM::API.in_span('example.greeting', attributes: { 'greeting.language' => 'en' }) do |span| + message = 'Hello from solarwinds_apm!' + span.add_event('greeting.generated', attributes: { 'message' => message }) + puts "Generated greeting: #{message}" +end + +puts +puts '--- Traces example complete ---' +sleep 5 # Ensure spans are exported before the process exits