使用 .NET 库为您的代码添加 Prometheus 指标
This is a .NET library for instrumenting your applications and exporting metrics to Prometheus.
The library targets the following runtimes (and newer):
This library allows you to instrument your code with custom metrics and provides some built-in metric collection integrations for ASP.NET Core.
The documentation here is only a minimal quick start. For detailed guidance on using Prometheus in your solutions, refer to the prometheus-users discussion group. You are also expected to be familiar with the Prometheus user guide. /r/PrometheusMonitoring on Reddit may also prove a helpful resource.
Four types of metrics are available: Counter, Gauge, Summary and Histogram. See the documentation on metric types and instrumentation best practices to learn what each is good for.
The Metrics class is the main entry point to the API of this library. The most common practice in C# code is to have a static readonly field for each metric that you wish to export from a given class.
More complex patterns may also be used (e.g. combining with dependency injection). The library is quite tolerant of different usage models - if the API allows it, it will generally work fine and provide satisfactory performance. The library is thread-safe.
After installing the library, you should:
/metrics).Minimal sample app (based on .NET 6 Console app template):
using var server = new Prometheus.KestrelMetricServer(port: 1234);
server.Start();
Console.WriteLine("Open http://localhost:1234/metrics in a web browser.");
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
Refer to the sample projects for quick start instructions:
| Name | Description |
|---|---|
| Sample.Web | ASP.NET Core application that produces custom metrics and uses multiple integrations to publish built-in metrics |
| Sample.Console | .NET console application that exports custom metrics |
| Sample.Console.DotNetMeters | Demonstrates how to publish custom metrics via the .NET Meters API |
| Sample.Console.Exemplars | .NET console application that attaches exemplars to some metrics |
| Sample.Console.NetFramework | Same as above but targeting .NET Framework |
| Sample.Console.NoAspNetCore | .NET console application that exports custom metrics without requiring the ASP.NET Core runtime to be installed |
| Sample.Grpc | ASP.NET Core application that publishes a gRPC service |
| Sample.Grpc.Client | Client app for the above |
| Sample.NetStandard | Demonstrates how to reference prometheus-net in a .NET Standard class library |
| Sample.Web.DifferentPort | Demonstrates how to set up the metric exporter on a different port from the main web API (e.g. for security purposes) |
| Sample.Web.MetricExpiration | Demonstrates how to use automatic metric deletion |
| Sample.Web.NetFramework | .NET Framework web app that publishes custom metrics |
The rest of this document describes how to use individual features of the library.
Nuget package for general use and metrics export via HttpListener or to Pushgateway: prometheus-net
Install-Package prometheus-net
Nuget package for ASP.NET Core middleware and stand-alone Kestrel metrics server: prometheus-net.AspNetCore
Install-Package prometheus-net.AspNetCore
Nuget package for ASP.NET Core Health Check integration: prometheus-net.AspNetCore.HealthChecks
Install-Package prometheus-net.AspNetCore.HealthChecks
Nuget package for ASP.NET Core gRPC integration: prometheus-net.AspNetCore.Grpc
Install-Package prometheus-net.AspNetCore.Grpc
Nuget package for ASP.NET Web API middleware on .NET Framework: prometheus-net.NetFramework.AspNet
Install-Package prometheus-net.NetFramework.AspNet
Counters only increase in value and reset to zero when the process restarts.
private static readonly Counter ProcessedJobCount = Metrics
.CreateCounter("myapp_jobs_processed_total", "Number of processed jobs.");
...
ProcessJob();
ProcessedJobCount.Inc();
Gauges can have any numeric value and change arbitrarily.
private static readonly Gauge JobsInQueue = Metrics
.CreateGauge("myapp_jobs_queued", "Number of jobs waiting for processing in the queue.");
...
jobQueue.Enqueue(job);
JobsInQueue.Inc();
...
var job = jobQueue.Dequeue();
JobsInQueue.Dec();
Histograms track the size and number of events in buckets. This allows for aggregatable calculation of quantiles.
private static readonly Histogram OrderValueHistogram = Metrics
.CreateHistogram("myapp_order_value_usd", "Histogram of received order values (in USD).",
new HistogramConfiguration
{
// We divide measurements in 10 buckets of $100 each, up to $1000.
Buckets = Histogram.LinearBuckets(start: 100, width: 100, count: 10)
});
...
OrderValueHistogram.Observe(order.TotalValueUsd);
Summaries track the trends in events over time (10 minutes by default).
private static readonly Summary RequestSizeSummary = Metrics
.CreateSummary("myapp_request_size_bytes", "Summary of request sizes (in bytes) over last 10 minutes.");
...
RequestSizeSummary.Observe(request.Length);
By default, only the sum and total count are reported. You may also specify quantiles to measure:
private static readonly Summary RequestSizeSummary = Metrics
.CreateSummary("myapp_request_size_bytes", "Summary of request sizes (in bytes) over last 10 minutes.",
new SummaryConfiguration
{
Objectives = new[]
{
new QuantileEpsilonPair(0.5, 0.05),
new QuantileEpsilonPair(0.9, 0.05),
new QuantileEpsilonPair(0.95, 0.01),
new QuantileEpsilonPair(0.99, 0.005),
}
});
The epsilon indicates the absolute error allowed in measurements. For more information, refer to the Prometheus documentation on summaries and histograms.
Timers can be used to report the duration of an operation (in seconds) to a Summary, Histogram, Gauge or Counter. Wrap the operation you want to measure in a using block.
private static readonly Histogram LoginDuration = Metrics
.CreateHistogram("myapp_login_duration_seconds", "Histogram of login call processing durations.");
...
using (LoginDuration.NewTimer())
{
IdentityManager.AuthenticateUser(Request.Credentials);
}
You can use Gauge.TrackInProgress() to track how many concurrent operations are taking place. Wrap the operation you want to track in a using block.
private static readonly Gauge DocumentImportsInProgress = Metrics
.CreateGauge("myapp_document_imports_in_progress", "Number of import operations ongoing.");
...
using (DocumentImportsInProgress.TrackInProgress())
{
DocumentRepository.ImportDocument(path);
}
You can use Counter.CountExceptions() to count the number of exceptions that occur while executing some code.
private static readonly Counter FailedDocumentImports = Metrics
.CreateCounter("myapp_document_imports_failed_total", "Number of import operations that failed.");
...
FailedDocumentImports.CountExceptions(() => DocumentRepository.ImportDocument(path));
You can also filter the exception types to observe:
FailedDocumentImports.CountExceptions(() => DocumentRepository.Im
暂无开放 Issues,或尚未同步最近议题。