What you’ll build
By the end of this guide, you’ll have:- A counter metric that tracks the total number of HTTP requests
- Code that increments the counter with labels for method, route, and status
- An understanding of how to export metrics for Prometheus to scrape
Prerequisites
Make sure you’ve installed PromGleam in your project before continuing.Create your first counter
Create a counter metric
A counter is a cumulative metric that represents a single monotonically increasing value. It can only increase or be reset to zero on restart.Create a counter to track HTTP requests:Let’s break down the parameters:
Call this setup function once when your application starts, before handling any requests.
- registry - The metric registry name (use
"default"for most cases) - name - A unique identifier for your metric (use snake_case)
- help - A description of what this metric measures
- labels - Label names for categorizing your metrics (empty list
[]if not needed)
Increment the counter
Now that your counter exists, you can increment it whenever an HTTP request is handled:Example usage in a request handler:
The number of label values must match the number of label names you specified when creating the counter. PromGleam will return an error if they don’t match.
Export metrics for Prometheus
Prometheus scrapes metrics by making HTTP requests to your application. You need to expose an endpoint that returns your metrics in a format Prometheus understands.Import the registry module:Create a metrics endpoint:When Prometheus scrapes
/metrics, it will receive output like:Complete example
Here’s everything together:Understanding counters
Counters are perfect for tracking:- Total number of requests served
- Number of tasks completed
- Number of errors encountered
- Any value that only increases over time
Don’t use counters for values that can decrease. For example, don’t use a counter for the number of active connections. Use a gauge instead.
What’s next?
You’ve successfully created your first metric! Here’s what to explore next:Gauge metrics
Learn about metrics that can go up and down
Histogram metrics
Measure distributions and percentiles
Wisp integration
See a complete example with the Wisp web framework
Metrics overview
Learn about all metric types and best practices