JF91.AppMetrics.InfluxDB2.Net7
1.0.0
我创建了这个包,以便您可以轻松地将 App.Metrics 集成到 ASP WEB API 中,以将收集到的指标发送到 InfluxDB2 服务器。
设置非常简单,只需安装 Nuget 包,将配置部分添加到 appsettings.json 并将服务注入到 program.cs 中。
请仔细按照说明进行操作。
安装 Nuget:
dotnet add package JF91.AppMetricsInfluxDB2 --version 1.2.0
appsettings.json
并根据您的需要进行修改: "MetricsOptions": {
"DefaultContextLabel": "MyCustomContext",
"Enabled": true
},
"MetricsWebTrackingOptions": {
"ApdexTrackingEnabled": true,
"ApdexTSeconds": 0.1,
"IgnoredHttpStatusCodes": [ 404 ],
"IgnoredRoutesRegexPatterns": [],
"OAuth2TrackingEnabled": true
},
"MetricEndpointsOptions": {
"MetricsEndpointEnabled": true,
"MetricsTextEndpointEnabled": true,
"PingEndpointEnabled": true,
"EnvironmentInfoEndpointEnabled": true
},
"MetricsReportingInfluxDb2Options": {
"InfluxDb2": {
"BaseUri": "http://127.0.0.1:8086",
"Organization": "metrics",
"Bucket": "metrics",
"Token": "changeme"
},
"HttpPolicy": {
"BackoffPeriod": "0:0:30",
"FailuresBeforeBackoff": 5,
"Timeout": "0:0:40"
},
"ReportInterval": "0:0:1"
}
launchSettings.json
中: "APPLICATION_NAME": "MyKickassApi"
builder.Build()
之前添加此内容: builder.Services.AddMetricsServices();
builder.WebHost.AddInfluxDb2AppMetrics(builder.Configuration);
builder.Build()
之后添加此内容: app.UseRequestsCounterMiddleware();
app.UseRequestsDurationMiddleware();
app.UseResponsesSizeMiddleware();
app.UseResponsesApdexMiddleware();
app.UseMetricsAllMiddleware();
app.UseMetricsAllEndpoints();
app.Run()
之前添加此内容: app.UseHttpStatusCodesCounterMiddleware();
1 - 创建拦截器中间件;
2 - 注入IMetrics
;
public class MyNewMetricMiddleware
{
private readonly RequestDelegate _next;
private readonly IMetrics _metrics;
public MyNewMetricMiddleware(RequestDelegate next, IMetrics metrics)
{
_next = next;
_metrics = metrics;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
var tags = new MetricTags
(
new[] { "Tag1-Key", "Tag2-Key" },
new[] { "Tag1-Value, "Tag2-Value }
);
_metrics.Measure.Counter.Increment
(
new CounterOptions
{
Name = "my-new-metric",
Context = "my-new-context",
MeasurementUnit = Unit.Calls,
Tags = tags
}
);
}
catch (Exception ex)
{
}
}
}
3 - 将中间件添加到应用程序管道:
builder.UseMiddleware();
1 - 将IMetrics
注入控制器:
public WeatherForecastController(ILogger logger, IMetrics metrics)
{
_logger = logger;
_metrics = metrics;
}
2 - 使用IMetrics
:
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable Get()
{
var tags = new MetricTags
(
new[] { "Tag1-Key", "Tag2-Key" },
new[] { "Tag1-Value, "Tag2-Value }
);
_metrics.Measure.Counter.Increment
(
new CounterOptions
{
Name = "my-new-metric",
Context = "my-new-context",
MeasurementUnit = Unit.Calls,
Tags = tags
}
);
return Enumerable.Range(1, 5).Select
(
index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}
)
.ToArray();
}