What is Open Telemetry?

Open Telemetry is a set of APIs, libraries, agents, and instrumentation to collect distributed traces and metrics from your applications. It is a vendor-neutral open standard for distributed tracing and metrics, and it is a part of the Cloud Native Computing Foundation (CNCF). Open Telemetry is designed to provide a consistent way to instrument and collect traces and metrics across different systems.

Why use Open Telemetry?

Open Telemetry is a powerful tool for understanding the performance of your distributed systems. It allows you to trace requests as they move through your system, and it provides you with detailed information about how long each part of the request took, and how long each part of the request spent waiting for other parts of the system. This information can be invaluable when diagnosing performance problems in your system.

Tracing and Metrics

Open Telemetry provides two main components: tracing and metrics. Tracing is used to trace requests as they move through your system, and it provides you with detailed information about how long each part of the request took, and how long each part of the request spent waiting for other parts of the system.

Metrics are used to collect and report metrics from your applications, and they provide you with detailed information about the performance of your applications.

Getting started with Open Telemetry & Jaeger for tracing

To get started with Open Telemetry, you can use Jaeger, an open-source, end-to-end distributed tracing system. Jaeger is a popular choice for implementing Open Telemetry because it is easy to set up and use, and it has a rich set of features for visualizing and analyzing traces.

run a local Jaeger instance in docker

To run a local Jaeger instance in docker, you can use the following command:

docker run 
    --env=COLLECTOR_ZIPKIN_HOST_PORT=:9411 
    --env=COLLECTOR_OTLP_ENABLED=true  
    -p 14250:14250 
    -p 14268:14268 
    -p 14269:14269 
    -p 16686:16686 
    -p 4317:4317 
    -p 4318:4318 
    -p 5778:5778 
    -p 6831:6831/udp 
    -p 6832:6832/udp 
    -p 9411:9411 
     -d jaegertracing/all-in-one:latest

This command will start a local Jaeger instance in docker, and it will expose the Jaeger UI on port 16686.

Implement Open Telemetry in your application

To implement Open Telemetry in your application, you need to add the Open Telemetry SDK to your application, and you need to configure it to send traces to your Jaeger instance. The following example shows how to set up Open Telemetry in a .NET REST API:

First, you need to install the following NuGet package:

  • OpenTelemetry (Base package)
  • OpenTelemetry.Exporter.Jaeger (Exporter for Jaeger)
  • OpenTelemetry.Instrumentation.AspNetCore (Instrumentation for ASP.NET Core)
  • OpenTelemetry.Instrumentation.EntityFrameworkCore (Instrumentation for Entity Framework Core)
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore

When you have installed the required NuGet packages, you can start using Open Telemetry in your application. The following example shows how to set up Open Telemetry in a .NET REST API:

using OpenTelemetry.Resources;
using OpenTelemetry.Trace;


//Add Open telemetry tracing
var serviceName = "ModularTracing.API";
var otlBuilder = builder.Services.AddOpenTelemetry();
otlBuilder.WithTracing(cfg =>
{
    cfg.AddSource(serviceName); // Register your service
    cfg.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName)); // Set the service name
    // Add ASP.NET Core instrumentation and enrich the traces with additional information
    cfg.AddAspNetCoreInstrumentation(aspnet =>
    {
        aspnet.EnrichWithHttpRequest = (activity, request) =>
        {
            activity.SetTag("http.request", request.Path);
        };
        aspnet.EnrichWithHttpResponse = (activity, response) =>
        {
            activity.SetTag("http.response", response.StatusCode.ToString());
        };
    });
    // Add Entity Framework Core instrumentation and enrich the traces with additional information
    cfg.AddEntityFrameworkCoreInstrumentation(efcore =>
    {
        efcore.EnrichWithIDbCommand = (activity, command) =>
        {
            activity.SetTag("db.command", command.CommandText);
            activity.SetTag("db.connectionstring", command.Connection.ConnectionString);
        };
    });
    // Add Jaeger exporter
    cfg.AddOtlpExporter(oltp =>
    {
        oltp.Endpoint = new Uri("http://localhost:4317");
       
    });
});

// Register the tracer provider in the service collection
builder.Services.AddSingleton(TracerProvider.Default.GetTracer(serviceName));

In the example above, the Open Telemetry SDK is added to the application, and it is configured to send traces to a local Jaeger instance. The traces are enriched with additional information from the ASP.NET Core and Entity Framework Core instrumentation, and they are exported to Jaeger using the Jaeger exporter.

The configuration enables the application to trace requests as they move through the system, and it provides detailed information about how long each part of the request took, and how long each part of the request spent waiting for other parts of the system. This information can be invaluable when diagnosing performance problems in your system.

Adding your own traces

To add your own traces to the Open Telemetry SDK, you can use the following code:

public class MyService
{
    private readonly Tracer _tracer;

    public MyService(Tracer tracer)
    {
        _tracer = tracer;
    }

    public void DoSomething()
    {
        using (var span = _tracer.StartActiveSpan("DoSomething"))
        {
            // Add your own code here
        }
    }
}

To add your own messages, or attributes to the trace, you can use the following code:

public class MyService
{
    private readonly Tracer _tracer;

    public MyService(Tracer tracer)
    {
        _tracer = tracer;
    }

    public void DoSomething()
    {
        using (var span = _tracer.StartActiveSpan("DoSomething"))
        {
            span.SetAttribute("my.attribute", "my value");
            span.AddEvent("my event");
            // Add your own code here
        }
    }
}

When you want to log an exception, you can use the following code:

public class MyService
{
    private readonly Tracer _tracer;

    public MyService(Tracer tracer)
    {
        _tracer = tracer;
    }

    public void DoSomething()
    {
        using (var span = _tracer.StartActiveSpan("DoSomething"))
        {
            try
            {
                // Add your own code here
            }
            catch (Exception ex)
            {
                // Set the status to error so it is visible in the trace
                span.setStatus(Status.Error.WithDescription(ex.Message));
                span.setStatus(Status.Error);
                span.RecordException(ex);
            }
        }
    }
}

In the examples above, the Open Telemetry SDK is used to add traces to the application, and it is used to add messages, attributes, and exceptions to the traces.

Conclusion

Open Telemetry is a powerful tool for understanding the performance of your distributed systems. It allows you to trace requests as they move through your system, and it provides you with detailed information about how long each part of the request took, and how long each part of the request spent waiting for other parts of the system. This information can be invaluable when diagnosing performance problems in your system.

Open Telemetry is a vendor-neutral open standard for distributed tracing and metrics, and it is a part of the Cloud Native Computing Foundation (CNCF). Open Telemetry is designed to provide a consistent way to instrument and collect traces and metrics across different systems. It is a powerful tool for understanding the performance of your distributed systems, and it is a valuable addition to any modern application.

Share the Post:

Related Posts

Gen AI

Phind

What is Phind Phind is an online search engine that uses AI to help you find the information you need.

Read More