Check out the Israel Data Stack: the ultimate resource for Israeli data companies.

[Digma] Using Decorators to Instrument Python Code With OpenTelemetry Traces

Using Decorators to Instrument Python Code With OpenTelemetry Traces
Better Programming
June 7, 2022

Roni Dover discusses the use of the Decorator design pattern in the context of tracing code. The author compares the implementation of tracing in .NET with the built-in support for function decorators in Python, which simplifies the process.

The need for tracing arises from the desire to define specific segments of code called "Spans" and track their execution and dependencies at runtime. However, instrumenting the code with tracing can be repetitive and challenging for large code bases.

The author proposes the use of a tracing decorator in Python to automate the instrumentation process. They provide an example implementation of a basic tracing decorator using Python decorators. The decorator automatically instruments a function by creating and naming a span, removing the need for boilerplate code. The default naming convention is based on the function name, but extensibility is offered for custom naming.

The code is tested to validate the functionality of the tracing decorator. An active tracing span is confirmed within a test method that has the decorator applied.

To make the process more efficient for classes, the decorator is modified to iterate over each function in a class and apply the decorator. Private functions are excluded from decoration. The modified code allows for class-level instrumentation without the need for individual function decoration.

A small issue is addressed where multiple decorators are applied to a function, resulting in multiple spans. To handle this, the decorator code checks whether a function has already been decorated and avoids reapplying the decorator.

The full source code is available in the Digma OpenTelemetry repository. Feedback, suggestions for improvement, and contributions are welcomed. The author also mentions another post on leveraging OpenTelemetry in development for those interested in observability.

Read more in Better Programming