Zum Fußzeileninhalt springen
.NET HILFE

Opentelemetry C# (Funktionsweise für Entwickler)

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.

Häufig gestellte Fragen

Was ist der Zweck von OpenTelemetry in der C#-Entwicklung?

OpenTelemetry bietet einen einheitlichen Ansatz, um Telemetriedaten wie Spuren, Metriken und Logs zu sammeln, zu verarbeiten und zu exportieren, wodurch Entwickler die Leistung von Anwendungen in Echtzeit überwachen und verstehen können.

Wie kann ich mit der Integration von OpenTelemetry in meine C#-Anwendung beginnen?

Beginnen Sie damit, die erforderlichen OpenTelemetry-Pakete über NuGet zu installieren, und konfigurieren Sie dann Ihre Anwendung, indem Sie die Methode 'ConfigureServices' in 'Startup.cs' ändern, um OpenTelemetry-Tracing und -Metriken einzubinden.

Welche Schritte sind erforderlich, um die Umgebung für OpenTelemetry in C# einzurichten?

Stellen Sie sicher, dass das .NET SDK auf Ihrem Computer installiert ist. Sie können die Installation überprüfen, indem Sie dotnet --version in Ihrer Befehlszeile ausführen.

Wie erstelle ich ein PDF in C# mit HTML-Inhalten?

Sie können die Klasse ChromePdfRenderer der IronPDF-Bibliothek verwenden, um HTML als PDF-Dokument zu rendern, und dann die Methode SaveAs verwenden, um das erzeugte PDF zu speichern.

Wie kann ich den PDF-Erstellungsprozess in einer C#-Anwendung überwachen?

Verwenden Sie OpenTelemetrys Tracer, um eine Aktivität zur PDF-Erstellung zu erstellen und benutzerdefinierte Tags hinzuzufügen, um relevante Informationen über den Prozess zu Überwachungszwecken zu protokollieren.

Was sind benutzerdefinierte Metriken und wie können sie in OpenTelemetry mit C# verwendet werden?

Benutzerdefinierte Metriken sind anwendungsspezifische Datenpunkte, die Sie durch manuelle Instrumentierung Ihres Codes mit den Klassen Meter und Counter von OpenTelemetry sammeln können.

Wie kann ich eine zuverlässige PDF-Generierung in C# gewährleisten?

Verwenden Sie die IronPDF-Bibliothek, um PDF-Dokumente zuverlässig zu erstellen, zu bearbeiten und darzustellen. IronPDF bietet robuste Funktionen, um qualitativ hochwertige PDF-Ausgaben in Ihren Anwendungen sicherzustellen.

Gibt es Lizenzoptionen für Bibliotheken, die bei der Erstellung von PDFs in C# helfen?

IronPDF bietet eine kostenlose Testversion für Produktionstests, mit Lizenzen, die ab 399 USD beginnen, wodurch es Entwicklern ermöglicht wird, alle Funktionen zu erkunden.

Wie kann ich meine OpenTelemetry-Integration in einer C#-Anwendung testen?

Führen Sie Ihre Anwendung aus und tätigen Sie Anfragen über einen Webbrowser oder Tools wie curl, und beobachten Sie die Telemetriedaten wie Traces und Metriken, die auf der Konsole ausgegeben werden.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen