PYTHON HELP

OpenTelemetry in Python Applications

Published July 1, 2024
Share:

Effective document generation and observability are essential foundations for developing scalable and resilient systems in contemporary software development. Developers can instrument, gather, and analyze observable data from distributed systems using OpenTelemetry, an open-source observability platform.

Developers can easily create, modify, and output PDF documents with IronPDF, a robust .NET framework. This article will discuss the integration of OpenTelemetry Python with IronPDF, demonstrating how these two technologies work together to improve observability and document generation potential.

Developers can access an extensive feature set for instrumenting, gathering, and exporting open telemetry and data from distributed systems with the OpenTelemetry API and SDK packages, an OpenTelemetry project implementation in Python.

OpenTelemetry Python (How It Works For Developers): Figure 1 - OpenTelemetry homepage

OpenTelemetry Features

Let's examine OpenTelemetry instrumentation for Python's salient features:

Distributed Tracing

  • Distributed tracing, which lets developers follow the path of requests through dispersed systems, is made possible by OpenTelemetry for Python.
  • Traces offer insight into the sequence of requests, including the dates and times of service contacts.
  • Python programs can be instrumented by developers to record spans, which are discrete actions or parts of a distributed trace.

Metrics Gathering

  • OpenTelemetry Python facilitates metrics import MeterProvider, which gathers numerical data regarding the behavior and performance of the system.
  • Developers may instrument their applications to gather measurements like latency, throughput, error rates, and resource usage.
  • By offering insights into usage patterns, performance trends, and system health.

Context Propagation

  • Context propagation is made easier by the OpenTelemetry API package, which makes sure that distributed context—such as trace and span context—is propagated across service boundaries.
  • Telemetry data can be correlated and contextualized as it moves through the system due to context propagation, which preserves the data's continuity and consistency.

Libraries of Instrumentation

  • OpenTelemetry Python makes it simple to instrument existing Python applications by providing instrumentation packages for widely used frameworks, libraries, and protocols.
  • Integrations for web frameworks (like Flask and Django), database clients (like SQLAlchemy and Pymongo), messaging systems (like Kafka and RabbitMQ), and more can be found in instrumentation libraries.

Ecosystem of Exporters

  • A range of exporters provided by OpenTelemetry Python enables developers to export telemetry data to different observability systems and backends.
  • Integrations with observability platforms like Jaeger, Zipkin, Prometheus, AWS X-Ray, Google Cloud Trace, and others are supported by exporters.
  • Exporters can be set up by developers to transfer telemetry data to one or more backends for long-term storage, analysis, and display.
  • Variable sampling techniques are supported by OpenTelemetry Python to regulate the quantity of telemetry data gathered.
  • Developers have the option to apply custom sampling logic, set sampling to sample a certain percentage of traces, or sample according to predefined parameters (such as request headers or routes).

Contextual Recordkeeping

  • Tools for recording contextual data in addition to telemetry data are available with the OpenTelemetry Python SDK.
  • Developers can add trace and span context to log messages with contextual logging, which gives more context for troubleshooting and debugging.

Create and Configure OpenTelemetry Python

Set Up OpenTelemetry Configuration

To set up OpenTelemetry for your project, you can start by installing the necessary packages using pip install opentelemetry-exporter-jaeger.

pip install opentelemetry-exporter-jaeger
PYTHON

Afterward, install the OpenTelemetry Python SDK using the following command pip install opentelemetry-sdk.

pip install opentelemetry-sdk
PYTHON

The opentelemetry-api pip package provides a comprehensive API for instrumentation, and it also offers automatic instrumentation making it easier to instrument your applications. An alternative way of doing it could be using the export-import BatchSpanProcessor method to ensure efficient telemetry data exporting.

To define OpenTelemetry SDK parameters, create a configuration file. The configuration file otel_config.py serves as an example. Ensure all your imports such as resources import Resource and trace import TracerProvider are present to set up the code example without any errors.

from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

from opentelemetry.exporter.jaeger.thrift import JaegerExporter

# Configure Jaeger exporter
jaeger_exporter = JaegerExporter(
    agent_host_name="localhost",
    agent_port=6831,
)

# Create a TracerProvider with Jaeger exporter
tracer_provider = TracerProvider(resource=Resource.create({'service.name': 'my-python-service'}))
tracer_provider.add_span_processor(BatchSpanProcessor(jaeger_exporter))
trace.set_tracer_provider(tracer_provider)
PYTHON

Within this configuration file:

  • The Jaeger exporter is set up to export traces to a localhost Jaeger agent.
  • Using the Jaeger exporter, we construct a TracerProvider and configure it to be the global tracer provider.
  • For our Python program, we provide the service name.

Initialize OpenTelemetry in Your Application

Import the otel_config module into your Python program, then initialize OpenTelemetry at the outset with the following example Python code:

from opentelemetry import trace
from otel_config import tracer_provider

# Initialize OpenTelemetry
trace.get_tracer(__name__)
PYTHON

By doing this, the configuration found in otel_config.py is initialized for OpenTelemetry instrumentation.

Instrument Your Application

Use OpenTelemetry to instrument your Python program so that it can record traces. You have two options for instrumenting your code: manually or via the built-in libraries. This is an illustration of a few manual instrumentation calls:

from opentelemetry import trace

# Start a span
with trace.get_tracer(__name__).start_as_current_span("example_span"):
    # Your code here
    pass
PYTHON

View Traces in Jaeger UI

To see and examine the recorded traces, go to the Jaeger user interface. To view the traces that the OpenTelemetry collector records, open the Jaeger UI in your web browser (usually at http://localhost:16686) and choose your service name.

You have successfully established and configured OpenTelemetry Python in your application by following these instructions. Now, you can see how your Python program behaves and performs by using OpenTelemetry to record traces and export them to the Jaeger backend.

Getting Started with IronPDF

What is IronPDF?

With the powerful .NET library IronPDF from Iron Software, developers can create, edit, and present PDF documents within .NET applications. Developers can use IronPDF to programmatically create PDF documents from a range of sources, such as pre-existing PDF files, HTML text, URLs, and images. Let's take a closer look at IronPDF's features:

OpenTelemetry Python (How It Works For Developers): Figure 2 - IronPDF homepage

Converting HTML to PDF

Developers may easily convert HTML content into PDF files with IronPDF. By using HTML text as input, developers can produce visually rich PDF documents with formatting, images, and styles.

Convert URL to PDF

Developers can generate PDF documents directly from URLs by using IronPDF. One excellent application for this functionality is capturing content from web pages or dynamically created content from web apps.

Converting Image to PDF

With IronPDF, images in PNG, JPEG, and BMP formats can be converted to PDF documents. This feature lets app developers create PDF documents from photos, which is helpful for apps for things like making picture albums or incorporating photos into PDF files.

How to Install IronPDF

After making sure Python is installed on your computer, use pip to install IronPDF.

pip install ironpdf
PYTHON

Using OpenTelemetry to Generate a PDF Document with IronPDF

Add the following code below OpenTelemetry's initialization to use IronPDF to create a PDF document:

from ironpdf import ChromePdfRenderer
from opentelemetry import trace

# Generate PDF document with IronPDF
with trace.get_tracer(__name__).start_as_current_span("pdf_generation"):
    iron_pdf = ChromePdfRenderer()
    html_content = "<html><body><h1>Hello, IronPDF!</h1></body></html>"

    pdf_content = iron_pdf.render_html_as_pdf(html_content)

    # Save or send the PDF content as needed
    with open("output.pdf", "wb") as file:
        file.write(pdf_content)
PYTHON

In this passage of code:

  • Utilizing the OpenTelemetry tracer, we begin a new span called pdf_generation.
  • We use IronPDF to turn HTML material into a PDF document during this time.
  • A file called output.pdf contains the generated PDF material.

OpenTelemetry Python (How It Works For Developers): Figure 3 - Example output generated from the code above

Conclusion

Finally, the combination of observability and document-generating capabilities in Python applications is provided by the OpenTelemetry Python and IronPDF connection. Developers can easily create professional-looking documents on the fly while gaining better insights into system performance by integrating distributed tracing and metrics collecting with dynamic PDF generation.

The collaboration between OpenTelemetry Python and IronPDF emerges as a potent enabler, enabling developers to create reliable, scalable, and performant applications, as enterprises strive for efficiency and excellence in their software solutions.

A lifetime license is included with IronPDF, which is fairly priced when purchased in a bundle. The bundle is a great deal at just $749, and it only needs to be bought once for several systems. Online engineering help is available to license holders 24/7. Please visit the website to learn more about the charge. Visit this page to learn more about the products sold by Iron Software.

< PREVIOUS
Matplotlib Python Guide for Beginners
NEXT >
Retrying Functions with Tenacity in Python

Ready to get started? Version: 2024.11.1 just released

Free pip Install View Licenses >