OpenTelemetry Jinja2 Instrumentation

0.62b0 · active · verified Thu Apr 09

The `opentelemetry-instrumentation-jinja2` library provides OpenTelemetry instrumentation for Jinja2, automatically tracing template loading, compilation, and rendering operations. It is part of the `opentelemetry-python-contrib` repository, which typically follows a monthly release cadence. As of the current version, many instrumentations within this contrib repository are still in a beta state, indicating ongoing development and potential for API changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry with Jinja2 instrumentation. It configures a basic `TracerProvider` with a `ConsoleSpanExporter` to print traces to the console, then instruments Jinja2, and finally renders a simple template to generate traces for loading, compiling, and rendering.

import os
from jinja2 import Environment, FileSystemLoader
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.jinja2 import Jinja2Instrumentor

# 1. Setup OpenTelemetry Tracer Provider and Exporter
# For simplicity, we use ConsoleSpanExporter to print traces to console
resource = Resource.create({"service.name": "jinja2-example"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# 2. Instrument Jinja2
Jinja2Instrumentor().instrument()

# 3. Create a dummy template file for demonstration
# In a real application, you'd have a 'templates' directory.
if not os.path.exists('templates'):
    os.makedirs('templates')
with open('templates/hello.html', 'w') as f:
    f.write('<h1>Hello, {{ name }}!</h1><p>Today is {{ date }}.</p>')

# 4. Use Jinja2 as usual
env = Environment(loader=FileSystemLoader("templates"))
tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("render-page"):
    template = env.get_template("hello.html")
    output = template.render(name="World", date="April 9, 2026")
    print(f"\nRendered Output:\n{output}")

print("\nJinja2 instrumentation complete. Check console for traces.")

view raw JSON →