Skip to footer content
.NET HELP

Opentelemetry C# (How It Works For Developers)

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
dotnet new web -o MyTelemetryApp
cd MyTelemetryApp
SHELL

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>
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>
SHELL

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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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)
$vbLabelText   $csharpLabel

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
curl http://localhost:5000
SHELL

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.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

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
dotnet add package IronPDF
SHELL

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
$vbLabelText   $csharpLabel

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.

Frequently Asked Questions

What is OpenTelemetry?

OpenTelemetry is a set of tools, APIs, and SDKs that collect, process, and export telemetry data like traces, metrics, and logs from applications. It provides a unified way to monitor and understand application performance in real-time.

How does OpenTelemetry benefit .NET developers?

OpenTelemetry helps .NET developers monitor their applications closely, understand performance in real-time, and identify issues quickly by automatically enabling tracing and metrics collection for .NET apps.

What do I need to set up the environment for OpenTelemetry in C#?

You need to have the .NET SDK installed on your machine. You can check your .NET SDK version using 'dotnet --version'.

How can I integrate OpenTelemetry into my C# project?

To integrate OpenTelemetry, add necessary packages via NuGet, configure OpenTelemetry in your application, and modify the 'ConfigureServices' method in 'Startup.cs' to include OpenTelemetry tracing and metrics.

How can I collect custom metrics using OpenTelemetry in C#?

You can collect custom metrics by manually instrumenting your code to create and record metrics using OpenTelemetry's Meter and Counter classes.

How can I ensure reliable PDF generation in my C# application?

You can use the IronPDF library to generate, manipulate, and render PDF documents in C#. It allows you to monitor and ensure the performance and reliability of PDF generation processes within your applications.

How can I generate a PDF in a C# application?

To generate a PDF, you can use a library such as IronPDF's ChromePdfRenderer class to render HTML as a PDF document, and save the PDF using the SaveAs method.

How can I monitor PDF generation processes?

You can monitor PDF generation processes by creating an activity using a tool like OpenTelemetry's Tracer and adding custom tags to log relevant information about the PDF generation process.

What are the basic steps to test my OpenTelemetry integration in a C# application?

Run your application and make requests to it using a web browser or tools like curl. Observe telemetry data such as traces and metrics printed to the console.

Are there trials or licenses available for libraries that assist in generating PDFs?

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

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.