.NET ヘルプ

Opentelemetry C#(開発者向けの仕組み)

OpenTelemetryは、トレース、メトリクス、ログのようなテレメトリーデータを収集、処理、およびエクスポートするために協力して動作するツール、API、SDKのセットです。 このチュートリアルは、初心者がC#アプリケーションにOpenTelemetryを拡張メソッドを使用して統合する方法を理解するのを助けることを目的としており、.NETアプリケーションを効果的に監視するための組み込みメトリクスの収集に焦点を当てています。 私たちはまた、C#でのPDF生成のためのIronPDFライブラリについて学びます。

OpenTelemetryの紹介

Opentelemetry C#(開発者にどのように機能するか):図 1 - OpenTelemetry

OpenTelemetry は、アプリケーションからあらゆる種類のデータを収集するための統一された方法を提供します。 .NET開発者にとって、OpenTelemetryの統合は、アプリケーションをより詳細に監視し、リアルタイムでのパフォーマンスを理解し、問題を迅速に特定することができます。 OpenTelemetryのインスツルメンテーション・ライブラリは、.NETアプリのトレースとメトリクス収集を自動的に可能にします。

OpenTelemetryフレームワークで収集されたメトリクスにより、開発者は.NETランタイム環境について貴重な洞察を得ることができます。 OpenTelemetryの.NET実装は、.NETランタイムをサポートしており、.NET Coreおよび.NET Frameworkを含みます。 標準化されたテレメトリデータ収集のために、OpenTelemetryプロトコルに準拠しています。

環境の設定

始めるには、マシンに.NET SDKがインストールされている必要があります。Visual Studioを使用している場合、おそらく.NET SDKが同梱されています。 現在の .NET SDK バージョンを確認するには、コマンドラインを開いて次のコマンドを実行してください:

dotnet --version
dotnet --version
SHELL

次に、以下のコマンドを実行して新しい .NET Web プロジェクトを作成します:

dotnet new web -o MyTelemetryApp
cd MyTelemetryApp
dotnet new web -o MyTelemetryApp
cd MyTelemetryApp
SHELL

このコマンドは、MyTelemetryApp という名前のディレクトリに新しい ASP.NET Core プロジェクトを作成します。

OpenTelemetryの統合

必要なパッケージの追加

まず、必要な OpenTelemetry パッケージをプロジェクトに追加します。 ターミナルを開いて、プロジェクトのディレクトリに移動してください。 それから、NuGetパッケージマネージャー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

を各パッケージの最新バージョンに置き換えてください。

アプリケーションでのOpenTelemetryの設定

必要なパッケージを追加した後、アプリケーションでOpenTelemetryを構成する必要があります。 これはOpenTelemetry SDKを設定し、どのテレメトリーデータを収集するかを指定することを含みます。 OpenTelemetryは、.NETアプリケーションとシームレスに統合するためのインストゥルメンテーションライブラリを提供します。

プロジェクト内のStartup.csファイルを開き、ConfigureServicesメソッドを次のコードスニペットに示すようにOpenTelemetryを含むように変更します。

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

次のコードスニペットは、OpenTelemetryを設定してASP.NET CoreアプリケーションおよびHTTPクライアント呼び出しからテレメトリーデータを収集し、このデータをコンソールにエクスポートする方法を示しています。 AddAspNetCoreInstrumentation メソッドは、ASP.NET Core アプリへの受信 HTTP リクエストの計装を自動的に有効にします。

メトリクス収集

メトリクスを収集するために、OpenTelemetry Metrics API を設定する必要があります。

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

このセットアップにより、ASP.NET CoreおよびHTTPクライアントのインストゥルメンテーションから組み込みメトリクスを収集し、それらをコンソールにエクスポートして簡単に表示することができます。

カスタムメトリクスの作成

OpenTelemetryは多くの有用なメトリクスを自動的に収集しますが、アプリケーション固有のカスタムメトリクスを収集したい場合もあります。 インスツルメンテーション・ライブラリによって提供される拡張メソッドを利用することで、遠隔測定を自動的に収集するだけでなく、開発者は放出されるメトリクスをより詳細に制御できるようになります。 これは、カスタムメトリクスを作成および記録するように手動でコードに計装することによって達成できます。

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

このコードスニペットは、リクエストごとのパスをタグ付けし、アプリケーションへのリクエストをカウントするカスタムメトリクスを作成する方法を示しています。 OpenTelemetryによって提供される拡張メソッドを活用することで、開発者はテレメトリーデータ収集プロセスをより詳細に制御することができます。

統合のテスト

アプリケーションをコマンドラインまたはVisual Studioを使用して実行します。 ウェブブラウザでそのURLにアクセスするか、curlのようなツールを使用してアプリケーションにいくつかのリクエストを送信します。 コンソール出力にトレースやメトリクスを含むテレメトリデータが表示されるはずです。

curl http://localhost:5000
curl http://localhost:5000
SHELL

IronPDFの紹介

Opentelemetry C#(開発者のための仕組み):図2 - IronPDF

IronPDFは、C#開発者向けの強力なライブラリであり、.NETアプリケーション内で直接PDFドキュメントの生成、操作、およびレンダリングを可能にします。 この機能は、特にレポート、請求書、またはHTMLを使用したWebアプリケーションからのドキュメントベースの出力に役立ちます。IronPDFをOpenTelemetryと組み合わせることで、開発者はアプリケーション内でのPDF生成プロセスのパフォーマンスと信頼性を監視でき、スムーズなユーザーエクスペリエンスを確保します。

IronPDFは、元のレイアウトとスタイルを正確に保持してHTMLからPDFへの変換に優れています。 それは、レポート、請求書、およびドキュメントなどのWebベースのコンテンツからPDFを作成するのに最適です。 IronPDFはHTMLファイル、URL、生のHTML文字列をサポートしており、簡単に高品質な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");
    }
}
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

IronPDFの設定

まず、IronPDFを.NETプロジェクトに追加する必要があります。 この処理はNuGetパッケージマネージャーを使用して行うことができます。 ターミナルを開いて、プロジェクトのディレクトリに移動してください。 次に、以下のコマンドを実行してIronPDFをインストールします:

dotnet add package IronPDF
dotnet add package IronPDF
SHELL

IronPDFを使用したPDFの生成とOpenTelemetryによる監視

以下は、シンプルなPDFドキュメントを生成し、OpenTelemetryを使用してその操作を監視する方法の例です。 以下の例では、前述のようにOpenTelemetryをアプリケーションに既に設定していることを前提としています。

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

この例では、新しいサービスクラスPdfServiceを作成し、PDFドキュメントを生成するためのメソッドGeneratePdfを含めます。 私たちは、HTMLをPDFドキュメントとしてレンダリングするためにChromePdfRendererクラスを使用します。 OpenTelemetryを使用して、この操作を監視するために「Generate PDF」という名前の新しいアクティビティを開始します。 PDF生成プロセスに関する追加のコンテキストを提供するために、PDFのサイズ、コンテンツタイプ、出力パスなどの情報をカスタムタグとしてアクティビティに追加します。 私たちは同じアクティビティ内でエラーを適切にログに記録するために、例外もキャッチします。

結論

Opentelemetry C#(開発者への適用方法): 図3 - ライセンス

.NET アプリケーションに OpenTelemetry を統合することで、貴重なテレメトリーデータを収集し、アプリケーションのパフォーマンスや動作に関する洞察を提供できます。 このチュートリアルの手順に従うことで、.NET ウェブアプリケーションの基本的なトレーシングおよびメトリクス収集を設定しました。 さらに実験を進めて、テレメトリデータを外部のモニタリングツールにエクスポートする機能や、トレースとメトリクスと共にログを収集する機能など、より高度なOpenTelemetry機能を探索してください。

IronPDFはその完全な機能をテストするためにIronPDFの無料トライアルを提供しています。 ライセンスは399ドルから。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
C# スパン(開発者のための仕組み)
次へ >
C# WebRTC(開発者向けの仕組み)