In modern software development, monitoring API performance and system health is critical for ensuring reliability, diagnosing issues, and improving application performance. Prometheus and Grafana are powerful open-source tools that allow developers to collect, store, and visualize metrics efficiently. In this guide, we will set up local monitoring for .NET Core APIs using Prometheus and Grafana, covering installation, configuration, metric collection, and dashboard visualization.
Why Use Prometheus and Grafana for .NET APIs?
- Prometheus: A widely used monitoring solution that scrapes metrics from targets and stores them in a time-series database.
- Grafana: A visualization tool that provides rich dashboards and alerting features for monitoring API health and performance.
- .NET Core Integration: .NET Core has built-in support for exporting metrics, making it easier to integrate with Prometheus.
Prerequisites
Before proceeding, ensure you have:
- .NET Core SDK (6.0 or later) installed.
- Docker installed for running Prometheus and Grafana containers.
- Basic knowledge of .NET Core APIs and Docker.
Step 1: Install and Configure Prometheus
1.1 Install Prometheus Using Docker
To quickly set up Prometheus locally, run the following command:
docker run -d --name=prometheus -p 9090:9090 \
-v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
1.2 Configure Prometheus for .NET APIs
Create a prometheus.yml configuration file in your project directory:
global:
scrape_interval: 15s # Set the scrape interval
scrape_configs:
- job_name: 'dotnet_api'
metrics_path: '/metrics'
static_configs:
- targets: ['host.docker.internal:5000']
1.3 Verify Prometheus Setup
Access Prometheus UI by visiting:
http://localhost:9090
Use the query interface to explore available metrics.
Step 2: Collect Metrics from .NET Core APIs
2.1 Add Prometheus NuGet Packages
In your .NET Core API project, install the prometheus-net package:
dotnet add package prometheus-net
2.2 Enable Metrics in Program.cs
Modify Program.cs
to expose Prometheus metrics:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Prometheus;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();
app.UseHttpMetrics(); // Collect HTTP request metrics
app.UseEndpoints(endpoints =>
{
endpoints.MapMetrics(); // Expose metrics at /metrics
});
app.Run();
Now, your API exposes metrics at http://localhost:5000/metrics
.
2.3 Test Metrics Collection
Start the API and verify that Prometheus can scrape metrics:
dotnet run
Visit http://localhost:5000/metrics
to check if metrics are being generated.
Step 3: Install and Configure Grafana
3.1 Install Grafana Using Docker
Run the following command to start a Grafana container:
docker run -d --name=grafana -p 3000:3000 grafana/grafana
Access Grafana at:
http://localhost:3000
Login with default credentials:
- Username: admin
- Password: admin
3.2 Add Prometheus as a Data Source
- Go to Configuration > Data Sources in Grafana.
- Click Add data source and select Prometheus.
- Set the Prometheus URL to:
http://host.docker.internal:9090
- Click Save & Test to verify the connection.
Step 4: Visualize API Performance with Dashboards
4.1 Create a New Dashboard
- Go to Dashboards and click New Dashboard.
- Add a Graph Panel and set Prometheus as the data source.
- Use the following query to visualize request duration:
http_server_requests_seconds_sum{job="dotnet_api"}
- Adjust visualization settings and save the dashboard.
4.2 Import Pre-Built Dashboards
Grafana has ready-to-use dashboards for .NET and Prometheus:
- Go to Dashboards > Import.
- Enter Dashboard ID: 10347 (for .NET Core Monitoring).
- Select Prometheus as the data source and import.
Step 5: Set Up Alerts for API Health
5.1 Define Alert Rules in Prometheus
Create an alert rule file alert.rules.yml:
groups:
- name: APIAlerts
rules:
- alert: HighErrorRate
expr: rate(http_requests_total{status="500"}[5m]) > 0.1
for: 2m
labels:
severity: critical
annotations:
summary: "High error rate detected in API"
Update prometheus.yml to load the alert rules:
rule_files:
- "alert.rules.yml"
Restart Prometheus to apply the changes.
5.2 Configure Alerts in Grafana
- Go to Alerting > Notification Channels.
- Add a new notification channel (Email, Slack, etc.).
- Set conditions like HTTP 5xx error rate and trigger alerts.
Conclusion
By following this guide, you've successfully set up Prometheus and Grafana for monitoring .NET Core APIs locally. You can now:
- Collect real-time metrics from your APIs.
- Visualize API performance using Grafana dashboards.
- Configure alerts for API failures.
This setup helps developers proactively monitor application performance, detect issues, and optimize API efficiency.