前回のブログでは、asp.net coreプロジェクトにPrometheusを導入する方法について説明しました。それはデモであるため、PrometheusとGrafanaはどちらもWindows版で、ローカルで実行されています。運用環境では、これらのサービスを企業のアーキテクチャに従って、適切な環境に配置できます。現時点では、これらのサービスはプラットフォームをまたぐこととコンテナ化がサポートされています。また、前回のブログで紹介したのはHTTPリクエストの基本情報テンプレートであり、今回のブログではカスタムPrometheusr指標タイプについて紹介します。
Prometheusには4種類の指標タイプがあります:Counter(カウンタ)、Gauge(ゲージ)、Histogram(ヒストグラム)、Summary(サマリー)。ビジネスの指標を収集し表示する場合、プロジェクトに対して侵襲的なプログラミングを要求します。プロジェクトがPrometheus.netを使用してPermetheusに接続する場合は、パッケージ内の静的メソッドMetrics.CreateCounter(),Metrics.CreateGauge(),Metrics.CreateSummary(),Metrics.CreateHistogram()を使用して静的指標収集器を作成し、ビジネス指標の収集を完了します。
具体的なデモを見てみましょう。
1、Counter:カウンタ、増加のみ
まずビジネスシナリオを設定します。例えば、商店において、ユーザー登録(/register)、注文(/order)、支払い(/pay)、発送(/ship)の4つのAPIがあり、コードは以下の通りです:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PrometheusSample.Models;
using PrometheusSample.Services;
using System;
using System.Threading.Tasks;
namespace PrometheusSample.Controllers
{
[ApiController]
[Route("[controller]")]
public class BusinessController : ControllerBase
{
private readonly ILogger<BusinessController> _logger;
private readonly IOrderService _orderService;
public BusinessController(ILogger<BusinessController> logger, IOrderService orderService)
{
_orderService = orderService;
_logger = logger;
}
/// <summary>
/// ユーザー登録
/// </summary>
/// <param name="username">ユーザー名</param>
/// <returns></returns>
[HttpPost("/register")]
public async Task<IActionResult> RegisterUser([FromBody] User user)
{
try
{
_logger.LogInformation("ユーザー登録");
var result = await _orderService.Register(user.UserName);
if (result)
{
return new JsonResult(new { Result = true });
}
else
{
return new JsonResult(new { Result = false });
}
}
catch (Exception exc)
{
_logger.LogCritical(exc, exc.Message);
return new JsonResult(new { Result = false, Message = exc.Message });
}
}
[HttpGet("/order")]
public IActionResult Order(string orderno)
{
try
{
_logger.LogInformation("注文");
return new JsonResult(new { Result = true });
}
catch (Exception exc)
{
_logger.LogCritical(exc, exc.Message);
return new JsonResult(new
{
Result = false,
Message = exc.Message
});
}
}
[HttpGet("/pay")]
public IActionResult Pay()
{
try
{
_logger.LogInformation("支払い");
return new JsonResult(new { Result = true });
}
catch (Exception exc)
{
_logger.LogCritical(exc, exc.Message);
return new JsonResult(new { Result = false, Message = exc.Message });
}
}
[HttpGet("/ship")]
public IActionResult Ship()
{
try
{
_logger.LogInformation("発送");
return new JsonResult(new { Result = true });
}
catch (Exception exc)
{
_logger.LogCritical(exc, exc.Message);
return new JsonResult(new { Result = false, Message = exc.Message });
}
}
}
}
(Translated by GPT)