Go
Adding version information

Adding version information to metrics in Go

Autometrics makes it easy to spot versions and commits that introduce errors or latency.

It produces a build_info metric and uses labels to expose the version, commit and branch information of your app to Prometheus.

Example:

build_info{branch="main",commit="5cc2aa5447907fbf0a7ddd",version="1.0.0",service_name="Billing",repository_url="",repository_provider=""} 1

Usage

To add version information to your metrics, simply add the relevant option parameters to the autometrics.Init() call:

main.go
autometrics.Init(
    autometrics.WithService("<service_name_here>"),
    autometrics.WithVersion("<version_here>"),
    autometrics.WithCommit("<git_commit_hash_here>"),
    autometrics.WithBranch("<git_branch_here>"),
)

All With... initialization settings are optional, and not setting them will leave the label empty like repository_url and repository_provider in the example above.

autometrics.With... options accept most fields as strings which you can set as you wish or use something like ldflags to set them at build time. Check the documentation on pkg.go.dev (for Prometheus version (opens in a new tab) or Open Telemetry version (opens in a new tab)) for more details about the initialization settings (all functions returning autometrics.Option).

Using ldflags to add version information at build time

Declare variables to hold the version information

main.go
var (
    Version = "development"
    Commit  = "n/a"
    Branch  string
)

Fill autometrics.BuildInfo in your autometrics.Init() call

main.go
autometrics.Init(
    autometrics.WithService("Billing"),
    autometrics.WithVersion(Version),
    autometrics.WithCommit(Commit),
    autometrics.WithBranch(Branch),
)

Build your app with ldflags

Now you can build your Go app using ldflags to set the version, commit and branch information.

Here's an example that uses git tags, commit hash and branch name:

Shell
go build -ldflags "-X main.Version=$(git describe --tags) -X main.Commit=$(git rev-parse HEAD) -X main.Branch=$(git rev-parse --abbrev-ref HEAD)"