OpenTelemetry Elasticsearch Instrumentation

0.62b0 · active · verified Fri Apr 10

This library provides instrumentation for the Python Elasticsearch client, allowing automatic capture of traces and metrics for interactions with Elasticsearch databases. It is part of the OpenTelemetry Python Contrib repository, currently at version 0.62b0, and follows the OpenTelemetry project's frequent release cadence, often with beta versions.

Warnings

Install

Imports

Quickstart

This quickstart configures a basic OpenTelemetry SDK with a `ConsoleSpanExporter` to print traces to the console. It then instruments the Elasticsearch client and attempts a `ping()` and `index()` operation. Spans representing these operations will be generated and printed to stdout. It includes error handling for cases where an Elasticsearch instance is not running.

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.elasticsearch import ElasticsearchInstrumentor
from elasticsearch import Elasticsearch, ConnectionError # Import ConnectionError for graceful handling

# 1. Configure OpenTelemetry Tracer Provider
# For demonstration, use ConsoleSpanExporter to print traces to stdout
resource = Resource.create({"service.name": "my-elasticsearch-app"})
tracer_provider = TracerProvider(resource=resource)
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
tracer_provider.add_span_processor(span_processor)
trace.set_global_tracer_provider(tracer_provider)

# 2. Instrument Elasticsearch
ElasticsearchInstrumentor().instrument()

# 3. Use the Elasticsearch client
# Ensure an Elasticsearch instance is running at this address.
# For a quick runnable example without a real ES instance, we'll catch ConnectionError.
try:
    # Replace with your Elasticsearch host if different. This will attempt connection.
    client = Elasticsearch("http://localhost:9200") 
    print("Attempting to ping Elasticsearch...")
    if client.ping():
        print("Elasticsearch connection successful! Spans should be visible.")
    else:
        print("Could not ping Elasticsearch. Check its status.")
    
    # Example of an index operation that will also be traced
    print("Indexing a document...")
    client.index(index="my-test-index", id=1, document={"message": "hello opentelemetry"})
    print("Document indexed. Check for additional spans.")

except ConnectionError as e:
    print(f"Could not connect to Elasticsearch: {e}")
    print("Spans for the connection attempt should still be generated, even if it failed.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

finally:
    # Ensure all spans are exported before exiting
    tracer_provider.shutdown()

view raw JSON →