.NET HELP

Opentelemetry C# (How It Works For Developers)

Published March 6, 2024
Share:

OpenTelemetry is a set of tools, APIs, and SDKs that work together to collect, process, and export telemetry data like traces, metrics, and logs from your applications. This tutorial aims to help beginners understand how to integrate OpenTelemetry in C# applications using the extension method, focusing on built-in metrics collection to monitor .NET applications effectively. We'll also learn about the IronPDF library for PDF generation in C#.

Introduction to OpenTelemetry

Opentelemetry C# (How It Works For Developers): Figure 1 - OpenTelemetry

OpenTelemetry provides a unified way to collect all kinds of data from your applications. For .NET developers, integrating OpenTelemetry means you can monitor your applications more closely, understand how they perform in real-time, and identify issues quickly. OpenTelemetry's instrumentation library automatically enables tracing and metrics collection for .NET apps.

With the metrics collected by the OpenTelemetry framework, developers gain valuable insights into the .NET runtime environment. The OpenTelemetry .NET implementation supports .NET runtime, including .NET Core and .NET Framework. It adheres to the OpenTelemetry protocol for standardized telemetry data collection.

Setting Up Your Environment

To start, you'll need to have the .NET SDK installed on your machine. If you're using Visual Studio, it likely came with the .NET SDK. You can check your current .NET SDK version by opening a command line and running:

dotnet --version

Next, create a new .NET Web project by running:

dotnet new web -o MyTelemetryApp
cd MyTelemetryApp

This command creates a new ASP.NET Core project in a directory named MyTelemetryApp.

Integrating OpenTelemetry

Adding Required Packages

First, add the necessary OpenTelemetry packages to your project. Open your terminal and navigate to your project directory. Then, install the following packages using the NuGet Package Manager CLI:

dotnet add package OpenTelemetry -Version <version>
dotnet add package OpenTelemetry.Extensions.Hosting -Version <version>
dotnet add package OpenTelemetry.Instrumentation.AspNetCore -Version <version>
dotnet add package OpenTelemetry.Exporter.Console -Version <version>

Replace with the latest version of each package.

Configuring OpenTelemetry in Your Application

After adding the necessary packages, you need to configure OpenTelemetry in your application. This involves setting up the OpenTelemetry SDK and specifying what telemetry data to collect. OpenTelemetry offers instrumentation libraries for seamless integration with .NET applications.

Open the Startup.cs file in your project and modify the ConfigureServices method to include OpenTelemetry as shown in the code snippet below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddOpenTelemetryTracing(builder =>
    {
        builder.AddAspNetCoreInstrumentation()
               .AddHttpClientInstrumentation()
               .AddConsoleExporter();
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddOpenTelemetryTracing(builder =>
    {
        builder.AddAspNetCoreInstrumentation()
               .AddHttpClientInstrumentation()
               .AddConsoleExporter();
    });
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	services.AddControllers()
	services.AddOpenTelemetryTracing(Sub(builder)
		builder.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddConsoleExporter()
	End Sub)
End Sub
VB   C#

This code snippet shows how to configure OpenTelemetry to collect telemetry data from ASP.NET Core applications and HTTP client calls, and then export this data to the console. The AddAspNetCoreInstrumentation method automatically enables instrumentation for incoming HTTP requests to ASP.NET Core apps.

Collecting Metrics

To collect metrics, you'll also need to configure the OpenTelemetry Metrics API, focusing on metrics rather than tracing.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddOpenTelemetryMetrics(builder =>
    {
        builder.AddAspNetCoreInstrumentation()
               .AddHttpClientInstrumentation()
               .AddConsoleExporter(options => options.Targets = ConsoleExporterOutputTargets.Console);
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddOpenTelemetryMetrics(builder =>
    {
        builder.AddAspNetCoreInstrumentation()
               .AddHttpClientInstrumentation()
               .AddConsoleExporter(options => options.Targets = ConsoleExporterOutputTargets.Console);
    });
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	services.AddControllers()
	services.AddOpenTelemetryMetrics(Sub(builder)
		builder.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddConsoleExporter(Sub(options) options.Targets = ConsoleExporterOutputTargets.Console)
	End Sub)
End Sub
VB   C#

This setup enables the collection of built-in metrics from ASP.NET Core and HTTP client instrumentation, exporting them to the console for easy viewing.

Creating Custom Metrics

While OpenTelemetry automatically collects many useful metrics, you might want to collect custom metrics specific to your application. Utilizing an extension method provided by the instrumentation library not only collects telemetry automatically but also gives developers more granular control over the metrics emitted. This can be achieved by manually instrumenting your code to create and record custom metrics.

var meter = new Meter("MyCustomMetrics", "1.0");
var counter = meter.CreateCounter<int>("custom_request_count", description: "Counts custom requests");
app.Use((context, next) =>
{
    counter.Add(1, new KeyValuePair<string, object>("path", context.Request.Path));
    return next();
});
var meter = new Meter("MyCustomMetrics", "1.0");
var counter = meter.CreateCounter<int>("custom_request_count", description: "Counts custom requests");
app.Use((context, next) =>
{
    counter.Add(1, new KeyValuePair<string, object>("path", context.Request.Path));
    return next();
});
Dim meter As New Meter("MyCustomMetrics", "1.0")
Dim counter = meter.CreateCounter(Of Integer)("custom_request_count", description:= "Counts custom requests")
app.Use(Function(context, [next])
	counter.Add(1, New KeyValuePair(Of String, Object)("path", context.Request.Path))
	Return [next]()
End Function)
VB   C#

This code snippet demonstrates how to create a custom metric that counts requests to your application, tagging each metric with the request path. By leveraging extension methods provided by OpenTelemetry, developers can exert more granular control over the telemetry data collection process.

Testing Your Integration

Run your application using the command line or Visual Studio. Make some requests to your application, either by navigating to its URL in a web browser or by using a tool like curl. You should see telemetry data, including traces and metrics, being printed to your console output.

curl http://localhost:5000

Introduction of IronPDF

Opentelemetry C# (How It Works For Developers): Figure 2 - IronPDF

IronPDF is a powerful library for C# developers, enabling the generation, manipulation, and rendering of PDF documents directly within .NET applications. This capability is especially useful for generating reports, invoices, or any document-based outputs from web applications using HTML, services, or desktop apps. Combining IronPDF with OpenTelemetry allows developers to monitor the performance and reliability of PDF generation processes within their applications, ensuring a smooth user experience.

Setting Up IronPDF

First, you need to add IronPDF to your .NET project. You can do this using the NuGet Package Manager. Open your terminal and navigate to your project directory. Then, run the following command to install IronPDF:

dotnet add package IronPDF

Generating a PDF with IronPDF and Monitoring with OpenTelemetry

Below is an example of how to generate a simple PDF document and monitor the operation using OpenTelemetry. The following example assumes you have already configured OpenTelemetry in your application as shown earlier.

using IronPdf;
using OpenTelemetry.Trace;
public class PdfService
{
    private readonly Tracer _tracer;
    public PdfService(Tracer tracer)
    {
        _tracer = tracer;
    }
    public void GeneratePdf()
    {
        // Create a new activity for this operation
        using var activity = _tracer.StartActivity("Generate PDF");
        // Simulate adding some attributes related to the operation
        activity?.SetTag("pdf.size", "A4");
        activity?.SetTag("pdf.content", "Hello World");
        try
        {
            // Initialize the PDF generator
            var renderer = new ChromePdfRenderer();
            // Generate a PDF from HTML
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
            // Save the PDF to a file
            var outputPath = "output.pdf";
            pdf.SaveAs(outputPath);
            // Log success
            activity?.SetTag("pdf.status", "Success");
            activity?.SetTag("pdf.outputPath", outputPath);
        }
        catch (Exception ex)
        {
            // Log any exceptions that occur during PDF generation
            activity?.SetTag("pdf.status", "Error");
            activity?.SetTag("pdf.error", ex.Message);
            throw;
        }
    }
}
using IronPdf;
using OpenTelemetry.Trace;
public class PdfService
{
    private readonly Tracer _tracer;
    public PdfService(Tracer tracer)
    {
        _tracer = tracer;
    }
    public void GeneratePdf()
    {
        // Create a new activity for this operation
        using var activity = _tracer.StartActivity("Generate PDF");
        // Simulate adding some attributes related to the operation
        activity?.SetTag("pdf.size", "A4");
        activity?.SetTag("pdf.content", "Hello World");
        try
        {
            // Initialize the PDF generator
            var renderer = new ChromePdfRenderer();
            // Generate a PDF from HTML
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
            // Save the PDF to a file
            var outputPath = "output.pdf";
            pdf.SaveAs(outputPath);
            // Log success
            activity?.SetTag("pdf.status", "Success");
            activity?.SetTag("pdf.outputPath", outputPath);
        }
        catch (Exception ex)
        {
            // Log any exceptions that occur during PDF generation
            activity?.SetTag("pdf.status", "Error");
            activity?.SetTag("pdf.error", ex.Message);
            throw;
        }
    }
}
Imports IronPdf
Imports OpenTelemetry.Trace
Public Class PdfService
	Private ReadOnly _tracer As Tracer
	Public Sub New(ByVal tracer As Tracer)
		_tracer = tracer
	End Sub
	Public Sub GeneratePdf()
		' Create a new activity for this operation
		Dim activity = _tracer.StartActivity("Generate PDF")
		' Simulate adding some attributes related to the operation
		If activity IsNot Nothing Then
			activity.SetTag("pdf.size", "A4")
		End If
		If activity IsNot Nothing Then
			activity.SetTag("pdf.content", "Hello World")
		End If
		Try
			' Initialize the PDF generator
			Dim renderer = New ChromePdfRenderer()
			' Generate a PDF from HTML
			Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
			' Save the PDF to a file
			Dim outputPath = "output.pdf"
			pdf.SaveAs(outputPath)
			' Log success
			If activity IsNot Nothing Then
				activity.SetTag("pdf.status", "Success")
			End If
			If activity IsNot Nothing Then
				activity.SetTag("pdf.outputPath", outputPath)
			End If
		Catch ex As Exception
			' Log any exceptions that occur during PDF generation
			If activity IsNot Nothing Then
				activity.SetTag("pdf.status", "Error")
			End If
			If activity IsNot Nothing Then
				activity.SetTag("pdf.error", ex.Message)
			End If
			Throw
		End Try
	End Sub
End Class
VB   C#

In this example, we create a new service class PdfService that includes a method GeneratePdf for generating a PDF document. We use IronPDF's ChromePdfRenderer class to render HTML as a PDF document. With OpenTelemetry, we start a new activity named "Generate PDF" to monitor this operation. We add custom tags to the activity to provide additional context about the PDF generation process, such as the size of the PDF, the content type, and the output path. We also catch any exceptions to log errors appropriately within the same activity.

Conclusion

Opentelemetry C# (How It Works For Developers): Figure 3 - Licensing

Integrating OpenTelemetry into your .NET applications allows you to collect valuable telemetry data, offering insights into your application's performance and behavior. By following the steps outlined in this tutorial, you've set up basic tracing and metrics collection for a .NET web application. Experiment further by exploring more advanced OpenTelemetry features, such as exporting telemetry data to external monitoring tools or collecting logs alongside traces and metrics.

IronPDF offers a free trial of IronPDF for production to test out its full capabilities. Licenses start from as low as $399.

< PREVIOUS
C# Span (How It Works For Developers)
NEXT >
C# WebRTC (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >