
In Go, you can use the Prometheus library to expose metrics about your application. You can use the `prometheus.NewGatherer()` function to create a new gatherer and register it with your application.
Prometheus is a popular monitoring system that provides a simple way to collect metrics from your application. It's widely used in the industry and has a large community of users and contributors.
To expose metrics, you can use the `http.Handler` interface to create a new HTTP handler that exposes the metrics. This handler can be registered with your application's HTTP server.
Prometheus provides a number of built-in metrics that you can use to monitor your application, including counters, gauges, and histograms. These metrics can be used to track a wide range of application performance and behavior metrics.
Consider reading: Golang Create
Metrics
Metrics are a crucial part of monitoring system health, and Prometheus provides four main types of metrics: Counter, Gauge, Summary, and Histogram. Each type is designed for a specific purpose, such as tracking values that only go up (like the number of HTTP requests) or capturing values that can fluctuate up or down (like memory usage).
A Counter is a metric that keeps track of a value that only goes up (or resets to zero when restarted), making it great for tracking things like the number of HTTP requests or total errors. For example, the metric `http_requests_total` tracks the total number of HTTP requests served.
Here are the four main metric types, along with their uses:
These metric types can be used to track various aspects of system health, and understanding their uses and limitations is essential for effective monitoring.
Recommended read: Golang Sap
Metrics
Metrics are a crucial aspect of monitoring and understanding system health. A Metric models a single sample value with its metadata being exported to Prometheus.
There are four main types of metrics in Prometheus: Counter, Gauge, Summary, and Histogram. A Counter is a metric that keeps track of a value that only goes up (or resets to zero when restarted), while a Gauge captures values that can fluctuate up or down.
A Histogram is a metric that tracks the distribution of values, showing how often different ranges of values occur. It's useful for measuring things like request durations or response sizes. A Summary provides statistics like averages and percentiles.
Here are the four main metric types with their corresponding descriptions:
In addition to these fundamental metric types, there are also vector versions, such as GaugeVec, CounterVec, SummaryVec, and HistogramVec, which are used for partitioning samples along dimensions called labels.
Data Analysis
A Histogram is a great tool for counting individual observations from an event or sample stream in configurable static buckets.
It provides a sum of observations and an observation count, similar to a Summary, but with the added benefit of quantiles that can be calculated using the histogram_quantile PromQL function.
This feature is particularly useful on the Prometheus server, where it can be used to gain a deeper understanding of the data.
However, Histograms do require the user to pre-define suitable buckets, which can be a limitation.
Fortunately, Native Histograms are available as an experimental feature, which can address this issue and provide more accurate results.
To create a Histogram instance, you can use the NewHistogram function, which creates a new Histogram based on the provided HistogramOpts.
The returned implementation also implements ExemplarObserver, making it safe to perform the corresponding type assertion.
This allows you to track Exemplars separately for each bucket, providing even more insight into the data.
GetLabelValues
GetLabelValues is a method that allows you to retrieve the label values for a specific metric. It returns the label values in the same order as the variable labels in the Desc.
You can use GetLabelValues to access the label values for a metric, and it will return the values in the same order as they appear in the Desc.
The label values are retrieved from the HistogramVec, and if the combination of label values is accessed for the first time, a new Histogram is created.
Calling GetLabelValues without using the returned Histogram will create a new Histogram without any observations.
VecOpts in 1.15.0

In version 1.15.0, two new types were added: GaugeVecOpts and HistogramVecOpts.
GaugeVecOpts bundles the options to create a GaugeVec metric.
To create a GaugeVec metric, it is mandatory to set GaugeOpts.
You can safely leave VariableLabels to its default value.
HistogramVecOpts bundles the options to create a HistogramVec metric.
To create a HistogramVec metric, it is mandatory to set HistogramOpts.
You can safely leave VariableLabels to its default value.
Labels
Labels are a collection of label name -> value mappings, commonly used with metric vector Collectors. They can be specified in Opts or used to create a Desc.
Labels are used in conjunction with the With(Labels) and GetMetricWith(Labels) methods of metric vector Collectors. This is one of their primary use cases.
A Labels collection is typically used to specify constant label pairs. This is a common way to create a Desc.
MustWithExemplars in v1.13.0
MustWithExemplars in v1.13.0 is a significant update that simplifies error handling for metrics.
This version introduces MustNewMetricWithExemplars, a function that panics where NewMetricWithExemplars would have returned an error.

MustNewMetricWithExemplars is designed to work best with MustNewConstMetric and MustNewConstHistogram, which are often used together.
The MustWithExemplars adapter is commonly used with the Timer type, and it has two primary use cases.
In these use cases, MustNewMetricWithExemplars provides a convenient way to handle errors without having to check for them explicitly.
NewMetricWithExemplars works best with MustNewConstMetric and MustNewConstHistogram, making them a great combination to use with MustWithExemplars.
Observer
The Observer interface is a crucial part of metrics collection, and it's used by Histogram and Summary to add observations. It's the interface that wraps the Observe method.
The Observe method is used to add observations, and it's a fundamental part of metrics collection. It's used to record the duration passed since a Timer was created.
The Observe method can also be used to observe a value together with an exemplar, thanks to the ExemplarObserver type. This allows for more detailed metrics collection.
ExemplarObserver replaces the currently saved exemplar with a new one, created from the provided value, the current time as timestamp, and the provided Labels.
Counter and Gauge
A Counter is a Metric that represents a cumulative count of events, such as the total number of HTTP requests made to a server. It's best used when the count always goes up, like in the example of HTTP requests.
To create a Counter, you can use a CounterVec, which is a Prometheus metric type that tracks a cumulative count of events and supports labels for categorization. This allows you to distinguish between different types of requests and provide detailed breakdowns for analysis.
In contrast, a Gauge is a Metric that represents a single numerical value that can arbitrarily go up and down. It's typically used for measured values like temperatures or current memory usage, but also "counts" that can go up and down, like the number of running goroutines.
Here's a comparison of Counters and Gauges:
A Gauge is useful for metrics where the value fluctuates over time, like the number of active users on a website. It can go up when a user logs in and down when a user logs out.
Exponential and Linear Buckets
Exponential and Linear Buckets are two types of buckets used in histograms. ExponentialBuckets creates regular buckets with upper bounds that are 'factor' times the previous bucket's upper bound.
The function ExponentialBuckets panics if 'count' is 0 or negative, if 'start' is 0 or negative, or if 'factor' is less than or equal to 1.
ExponentialBucketsRange creates buckets with a minimum value of 'min' and a maximum value of 'max'. The function panics if 'count' is 0 or negative, if 'min' is 0 or negative.
Exponential Buckets
Exponential Buckets are created using the ExponentialBuckets function, which takes three parameters: count, start, and factor. The function creates 'count' regular buckets, where the lowest bucket has an upper bound of 'start'.
Each following bucket's upper bound is 'factor' times the previous bucket's upper bound. This means that the upper bound of each bucket increases exponentially. The final +Inf bucket is not counted and not included in the returned slice.

The function panics if 'count' is 0 or negative, if 'start' is 0 or negative, or if 'factor' is less than or equal to 1. This ensures that the function is used correctly and doesn't produce invalid results.
ExponentialBucketsRange is a variation of the ExponentialBuckets function that creates 'count' buckets with a fixed minimum and maximum. The lowest bucket is 'min' and the highest bucket is 'max'. The final +Inf bucket is not counted and not included in the returned slice.
This function panics if 'count' is 0 or negative, or if 'min' is 0 or negative. It's essential to ensure that these parameters are valid to avoid panicking.
Linear Buckets
Linear Buckets are created with the LinearBuckets function, which takes three parameters: start, count, and width. The function creates 'count' regular buckets, each 'width' wide.
The start of the lowest bucket has an upper bound of 'start'. The returned slice is meant to be used for the Buckets field of HistogramOpts.
If you try to create linear buckets with a count of zero or negative, the function will panic. This is because a non-positive count doesn't make sense in this context.
Register and Unregister
Register is a shortcut for DefaultRegisterer.Register(c), which registers the provided Collector with the DefaultRegisterer.
Unregister removes the registration of the provided Collector from the DefaultRegisterer. It's a shortcut for DefaultRegisterer.Unregister(c), and more details can be found there.
The Registerer interface is used for registration purposes, rather than the Registry type directly. This allows users to use custom Registerer implementations, such as for testing purposes.
Additional reading: C Golang
Register
Register is a straightforward way to add your Collectors to the DefaultRegisterer. This is a shortcut for DefaultRegisterer.Register(c) and is used to register a single Collector.
Registering a Collector with the DefaultRegisterer is a common operation, and Register makes it easy to do so. In fact, Register is a shortcut for DefaultRegisterer.Register(c) which is used to register a single Collector.
If you need to register multiple Collectors at once, you can use the MustRegister function, which is a shortcut for DefaultRegisterer.MustRegister(cs...). This function will panic if any error occurs during registration.
Vec Delete

Vec Delete is a method used to delete metrics from a MetricVec.
It specifically looks for metrics with variable labels that match the labels passed in as an argument.
The method returns true if a matching metric is found and deleted, but it will always return false if the labels are inconsistent with the variable labels in the metric's description.
This method is used for the same purpose as DeleteLabelValues, but it's worth noting that the two methods have different pros and cons.
The method will not return an error if the number and names of the labels are inconsistent with those of the variable labels, but such inconsistent labels can never match an actual metric.
Collector and Registry
The Collector and Registry are two crucial components of the Prometheus system. They work together to collect metrics from various sources and expose them for monitoring.
A Collector is an interface implemented by anything that can collect metrics, and it must be registered for collection. The stock metrics provided by the package are also Collectors.
CollectorFunc is a convenient way to implement a Prometheus Collector without interface boilerplate. It's based on the DescribeByCollect method and can be used to register metric info for HTTP requests.
The Registry registers Prometheus collectors, collects their metrics, and gathers them into MetricFamilies for exposition. It implements Registerer, Gatherer, and Collector, and the zero value is not usable.
A Registry can be used for creating groups of metrics by implementing the Collector interface. This is shown in the example where a Registry is used to create groups of metrics.
Summary and Timer
Summary is a metric that captures individual observations and summarizes them in a traditional statistical manner. It provides the sum of observations, observation count, and rank estimations.
You can create a Summary instance using the NewSummary function, which takes SummaryOpts as an argument. The default Summary behavior will change in the upcoming v1.0.0 of the library, so it's recommended to set the desired rank estimations explicitly.
Rank estimations, such as the median and 99th percentile, cannot be aggregated in a meaningful way with the Prometheus query language. If you need aggregatable quantiles, consider using the Histogram metric type instead.
Readers also liked: How to Update a Github Using Golang
Summary

A Summary captures individual observations from an event or sample stream and summarizes them in a manner similar to traditional summary statistics.
The Summary type provides the median, the 90th and the 99th percentile of the latency as rank estimations by default, but this behavior will change in the upcoming v1.0.0 of the library.
To create Summary instances, use NewSummary, which creates a new Summary based on the provided SummaryOpts.
You cannot average or add rank estimations in a meaningful way with the Prometheus query language, so if you need aggregatable quantiles, consider using the Histogram metric type.
A typical use-case for Summary is the observation of request latencies, where you can get a median, 90th and 99th percentile of the latency as rank estimations.
SummaryVec
SummaryVec is a Collector that bundles a set of Summaries that all share the same Desc, but have different values for their variable labels. This allows you to count the same thing partitioned by various dimensions.
Using SummaryVec is useful if you want to track metrics like HTTP request latencies, partitioned by status code and method. For example, you could use it to see how long requests take for different status codes.
NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and partitioned by the given label names. This function is used to create instances of SummaryVec.
You should avoid using "quantile" as a label name when creating a SummaryVec, as it's an illegal label name in the Prometheus text format. If you try to use it, NewSummaryVec will panic.
Timer
A timer is a simple yet powerful tool that can help you stay on track and manage your time more effectively.
It's estimated that setting a timer for 25 minutes can increase productivity by up to 30%.
The Pomodoro Technique, a time management method, uses a timer to work in focused 25-minute increments, followed by a 5-minute break.
By using a timer, you can avoid distractions and stay focused on the task at hand.
Studies have shown that using a timer can reduce procrastination and increase motivation.
HTTP and Grafana
Grafana is a powerful tool for visualizing metrics, and integrating it with Prometheus is a great way to gain insights into your system's health.
To get started, you'll need to update your docker-compose.yaml file with the grafana/grafana image. This will set up Grafana using Docker.
You can then add a new data source and select Prometheus as the source, entering the URL http://prometheus:9090 to connect to your Prometheus instance.
To create a new dashboard, select Dashboard in the left-hand panel and then select the ‘New Dashboard’ button.
You might like: Golang Dashboard
HTTP Client
The HTTP Client is a crucial part of querying time series data from a Prometheus server.
It's located in the api/prometheus directory, which contains the client for the Prometheus HTTP API. This API allows you to write Go applications that can interact with a Prometheus server.
The client is still in its alpha stage, so it's not yet fully developed, but it's a promising tool for those who need to query time series data from Prometheus.
Integrating with Grafana
Integrating with Grafana is a crucial step in visualizing your metrics. To do this, you'll need to update your docker-compose.yaml file with the grafana/grafana image.
You'll also need to add a new data source in Grafana and select Prometheus as the source. Enter the URL http://prometheus:9090 to connect to your Prometheus instance.
Once you've added the data source, you can use the Grafana UI to create a new dashboard and add panels to visualize your Prometheus metrics. This will give you a clear view of your system's health and performance.
To create a new dashboard, select Dashboard in the left-hand panel and then select the 'New Dashboard' button. From there, you can add visualizations and select Prometheus as the data source.
Here's a step-by-step guide to setting up a new dashboard:
- Select Dashboard in the left-hand panel
- Click on 'New Dashboard'
- Click on 'Add Visualization'
- Select Prometheus as the data source
- Select metrics such as http_requests_total, http_request_duration_seconds, and active_connections
By following these steps, you'll be able to create a new dashboard and visualize your Prometheus metrics in Grafana.
Instrumenting and Exposing
The Prometheus directory contains the instrumentation library, which you can find on the Prometheus website to learn more about instrumenting applications.
To get started, you'll need to install the prometheus and promhttp packages, which provide the core library for defining and managing metrics, as well as an HTTP handler for exposing metrics in a Prometheus-compatible format.
You can integrate these packages into your Go application by modifying your main.go file to import the promhttp package, which provides an HTTP handler that serves metrics in a format that Prometheus can scrape.
If you visit the http://localhost:8000/metrics in your browser, you'll see the default metrics exposed by Prometheus, including standard Go runtime metrics and process metrics.
To disable these default metrics and only expose the metrics you care about, you'll need to create a custom registry and register only the metrics you want to expose.
By default, Prometheus uses the global registry, which automatically registers standard Go runtime metrics and process metrics. However, these metrics aren't usually essential for typical monitoring needs.
To expose only the metrics you explicitly register, you can pass your custom registry to promhttp.HandlerFor().
Here's a summary of the steps to expose metrics:
- Install the prometheus and promhttp packages.
- Modify your main.go file to import the promhttp package.
- Create a custom registry and register only the metrics you care about.
- Pass your custom registry to promhttp.HandlerFor() to expose only the metrics you explicitly register.
Featured Images: pexels.com


