asp.net core监控—引入Prometheus(二)
上一篇博文中,說明了怎么引進Prometheus到asp.net core項目中,因為是Demo,所以Prometheus和Grafana都是windows版本,本地執行的,生產環境上這些服務可以根據的公司的架構,放到適合的環境內,現在這些服務都支持跨平臺化和容器化。并且在上篇博客中展示的是http請求的基礎信息模板,本篇博客介紹自定義Prometheusr指標類型。
Prometheus有四種指標類型:Counter(計數器)、Gauge(儀表盤)、Histogram(直方圖)、Summary(摘要),如果對業務的指標進行收集展示,在項目中是侵入式編程的,如果項目使用Prometheus.net進行對接Permetheus,是通過該包中的靜態方法 Metrics.CreateCounter(),Metrics.CreateGauge(),Metrics.CreateSummary(),Metrics.CreateHistogram()來創建靜態指標收集器,完成對業務指標收集的。
我們先來看具體Demo。
1、Counter:計數器,只增不減
先設置個業務場景:比如做一個商城,有用戶注冊(/register),下訂單(/order),支付(/pay),發貨(/ship)四個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 });}}} }上面是基本的業務Controller,為了降低依賴,我們的業務指標收集統一到一個中間件中去收集,中間件根據請求的url,和返回的數據結果數據進行業務指標數據的收集,當然也可以引入action過濾器或MediatR等中介者模式的組件來隔離業務邏輯的開發與監控數據的采集。
本例是用中間件的方式,首先定義一個靜態的指標收集器:
定義中間件BusinessMetricsMiddleware
using Microsoft.AspNetCore.Http; using PrometheusSample.Models; using System.IO; using System.Threading.Tasks;namespace PrometheusSample.Middlewares {/// <summary>/// 請求記錄中間件/// </summary>public class BusinessMetricsMiddleware{private?readonly?RequestDelegate?_next;public BusinessMetricsMiddleware(RequestDelegate next){_next = next;}public async Task InvokeAsync(HttpContext context, MetricsHub metricsHub){var originalBody = context.Response.Body;try{using (var memStream = new MemoryStream()){//從管理返回的Response中取出返回數據,根據返回值進行監控指標計數context.Response.Body = memStream;await _next(context);memStream.Position = 0;string responseBody = new StreamReader(memStream).ReadToEnd();memStream.Position = 0;await memStream.CopyToAsync(originalBody);if (metricsHub.GetCounter(context.Request.Path) != null || metricsHub.GetGauge(context.Request.Path) != null){//這里約定所有action返回值是一個APIResult類型var result = System.Text.Json.JsonSerializer.Deserialize<APIResult>(responseBody, new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true });if (result != null && result.Result){//獲取到Countervar counter = metricsHub.GetCounter(context.Request.Path);if (counter != null){//計數counter.Inc();}}}}}finally{context.Response.Body = originalBody;}}} }中間件中,只要action請求返回的Result為true,就會計數,這樣做的前提條件是業務返回值有統一約定;但每個action返回不可能都一樣的,如果有特例,可以用action過濾器或中介者模式組件來對應。
再看一下Starup中是怎么配置這個中間件的:
MetricsHandle中,我們添加了四個action,分別對應的四個計數器,這樣,當這四個url有請求,并且返回值中的result=true時,就會往對應的計數器上計數。
這樣數據收集好了,現在開始在Grafana中配置顯示的圖表了:
訂單各狀態總數配置:
訂單各狀態30秒內數量跟蹤折線
最后的運行結果是:
總結實現自定義業務計數器步驟:
1、分析業務,規劃好監控跟蹤指標
2、定義指標收集器
3、侵入編程(盡量在開發時分離業務實現與監控指票的收集代碼)收集指標
4、開發grafana展示模板,完成展示
總結
以上是生活随笔為你收集整理的asp.net core监控—引入Prometheus(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net core监控—引入Pro
- 下一篇: ASP.NET Core Blazor