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

[Digma] Using the Decorator Pattern to Auto-Instrument .Net Classes With Otel Tracing

Using the Decorator Pattern to Auto-Instrument .Net Classes With Otel Tracing - Roni Dover, CTO Digma
Better Programming
June 1, 2022

Roni Dover discusses their experience with OpenTelemetry in .NET and points out some terminology confusion caused by the .NET implementation. They mention that an OpenTelemetry Span is called an 'Activity' in .NET, while 'ActivitySource' is referred to as a 'Tracer'. Despite this, the author appreciates the support for defining traces and spans using the built-in System.Diagnostics classes in .NET.

The author also addresses the issue of repetitive boilerplate code for setting up spans/activities in their projects. To solve this problem, they introduce the concept of decorators, which provide a way to wrap operations with OpenTelemetry activities. The .NET DispatchProxy class is used to create a generic wrapper for any interface, allowing the creation of a tracing decorator.

The post provides a step-by-step guide on creating a basic tracing decorator using DispatchProxy. The implementation includes overriding the Invoke method to wrap the decorated object's methods with an Activity. The author suggests using the decorator to wrap application classes and demonstrates how to do it using the .NET DI framework.

The author then explores further improvements to the initial implementation, such as adding attributes to customize the behavior of the decorator. They also mention potential future enhancements, including the ability to automatically instrument interface methods based on attributes and the ability to define a naming schema for spans.

Read more in Better Programming