ASP.NET Core アプリケーションへ Azure Monitor OpenTelemetry Distro を導入してみた

2024.02.17

いわさです。

先日 ASP.NET Core アプリケーション上から Azure Application Insights へカスタムメトリクスを発行しました。

上記はクラシック API を使って実装しているのですが、現在は OpenTelemetry を使った実装も行うことが出来ます。
また、公式ドキュメントでは「Application Insights の長期的な計画は、OpenTelemetry を使用してデータを収集することです。」と紹介されています。

ただ、「私たちは OpenTelemetry を将来の方向性と見なしていますが、古い SDK からのデータ収集を停止する計画はありません。 Azure OpenTelemetry Distros が Application Insights SDK の機能パリティに到達するには、まだなすべきことがある状況です。多くの場合、お客様は Application Insights SDK をかなり長い間使用し続けることを選択します。」とも言及されており、実際にいくつかの Application Insights の機能は OpenTelemetry 経由ではサポートされていません。

上記から現時点では積極的に OpenTelemetry へ移行すべきかというとそうではない状況のようです。

とはいえ、最近 OpenTelemetry を意識する機会も増えてきたのと、ドキュメントを見た感じだととても簡単にコードへの実装が出来るようなので、今回は Application Insights に対して OpenTelemetry 経由でアクセスする方法を試してみました。

.NET 8 で実装していますが、.NET Aspire などは使っていません。

Web API を作成

最低限の ASP.NET Core の Web API デフォルトテンプレートに実装します。

% dotnet --version
8.0.101
% dotnet new webapi
The template "ASP.NET Core Web API" was created successfully.

Processing post-creation actions...
Restoring /Users/iwasa.takahito/work/hoge0217opentelemetry/hoge0217opentelemetry.csproj:
  Determining projects to restore...
  Restored /Users/iwasa.takahito/work/hoge0217opentelemetry/hoge0217opentelemetry.csproj (in 1.28 sec).
Restore succeeded.

実行すると次のようにレスポンスが取得出来ます。

% dotnet run
Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5157
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /Users/iwasa.takahito/work/hoge0217opentelemetry
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
      Failed to determine the https port for redirect.


:

% curl http://localhost:5157/weatherforecast | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   381    0   381    0     0   120k      0 --:--:-- --:--:-- --:--:--  124k
[
  {
    "date": "2024-02-18",
    "temperatureC": 49,
    "summary": "Cool",
    "temperatureF": 120
  },
  {
    "date": "2024-02-19",
    "temperatureC": -5,
    "summary": "Scorching",
    "temperatureF": 24
  },
  {
    "date": "2024-02-20",
    "temperatureC": -8,
    "summary": "Warm",
    "temperatureF": 18
  },
  {
    "date": "2024-02-21",
    "temperatureC": 7,
    "summary": "Warm",
    "temperatureF": 44
  },
  {
    "date": "2024-02-22",
    "temperatureC": 24,
    "summary": "Cool",
    "temperatureF": 75
  }
]

Azure Monitor OpenTelemetry を有効にする

Azure Monitor OpenTelemetry Distro はマイクロソフトによってサポートされている OpenTelemetry のラッパーです。
こちらを使うことで有効化が簡単になり、Application Insights SDK を使ったトレース保存機能が使えたり、将来的にはまだサポートされていないライブメトリックスなどもサポートされる予定となっています。

上記の Azure 公式ドキュメントでもこちらを使った実装方法が紹介されていますのでこちらを使ってみます。

NuGet パッケージAzure.Monitor.OpenTelemetry.AspNetCoreとして提供されていますのでこちらをプロジェクトに追加します。

% dotnet add package Azure.Monitor.OpenTelemetry.AspNetCore
  Determining projects to restore...
  Writing /var/folders/4d/nhd1bp3d161crsn900wjrprm0000gp/T/tmpHVWUwV.tmp
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/8.0.101/trustedroots/codesignctl.pem'.

:

info : Writing assets file to disk. Path: /Users/iwasa.takahito/work/hoge0217opentelemetry/obj/project.assets.json
log  : Restored /Users/iwasa.takahito/work/hoge0217opentelemetry/hoge0217opentelemetry.csproj (in 7.24 sec).

ミドルウェアを追加します。

Program.cs

using Azure.Monitor.OpenTelemetry.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddOpenTelemetry().UseAzureMonitor();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

:

続いて Application Insights インスタンスを作成し、接続文字列を取得します。
取得した接続文字列を環境変数APPLICATIONINSIGHTS_CONNECTION_STRINGに設定します。

基本的な部分のみですが、有効化はこれだけで完了です。
Web API へリクエストを数回送信してみると、Application Insights 上で確認することが出来ました。

なお、コミュニティにより提供されている OpenTelemetry-Collector の Azure Monitor Exporer はマイクロソフトからはサポートされていないそうです。

さいごに

本日は Azure Monitor OpenTelemetry Distro を使ってみました。

最低限の部分だけとりあえずやってみましたが有効化だけならすぐ出来ますね。
前回行ったようなカスタムメトリクスの送信や、OpenTelemetry らしく他の宛先を追加するなど少しカスタマイズしてみたいと思います。