Prometheus Go Client Library

repository·main·Indexed 27 days ago

https://github.com/prometheus/client_golang

The official Prometheus client library for Go. It provides tools for application instrumentation via the prometheus package and a client for interacting with the Prometheus HTTP API for querying time series data. Additionally, it includes experimental support for Prometheus remote write APIs, including a remote write API client and a handler for applications to receive and store remote write requests.

Tokens
1.9K
Snippets
4
Records
12
Agent score
91%

What's inside client_golang

  1. Overview of Prometheus Go client library

    main

    The client_golang library provides two primary functionalities for working with Prometheus in Go:

    1. Application Instrumentation: Tools to add metrics to your application code so they can be scraped by a Prometheus server. These are located in the prometheus package.
    2. Prometheus HTTP API Client: A client for interacting with the Prometheus HTTP API, allowing Go applications to query time series data. This client is currently in an experimental/alpha stage.
  2. Overview of the Prometheus Go client library

    main
    The client_golang repository provides the official Prometheus client library for the Go programming language. It is used to instrument Go applications with Prometheus metrics and includes a client for interacting with the Prometheus HTTP API.
  3. Implement a Remote Write handler for applications

    main

    If your application needs to receive, handle, and store remote write requests, you can use remote.NewHandler.

    To use this, you must implement a storage backend that satisfies the required interface (e.g., a Store method that accepts a context, message type, and HTTP request).

    import (
        "net/http"
        "log"
        "github.com/prometheus/client_golang/exp/api/remote"
    )
    
    // ...
    
    type db {} // Your storage implementation
    
    func NewStorage() *db {}
    
    // Implement the storage interface
    func (d *db) Store(ctx context.Context, msgType remote.WriteMessageType, req *http.Request) (*remote.WriteResponse, error) {}
    
    // ...
    
    mux := http.NewServeMux()
    
    // Create the handler with your storage and optional logger
    remoteWriteHandler := remote.NewHandler(storage, remote.WithHandlerLogger(logger.With("component", "remote_write_handler")))
    
    // Register the handler at the standard remote write endpoint
    mux.Handle("/api/v1/write", remoteWriteHandler)
    
    server := &http.Server{
        Addr:    ":8080",
        Handler: mux,
    }
    if err := server.ListenAndServe(); err != nil {
        log.Fatal(err)
    }
  4. Instrument applications with the prometheus package

    main

    To add metrics to your Go application, use the instrumentation library located in the prometheus package. For detailed implementation steps, refer to the official Prometheus guide for Go applications.

    Simple usage examples can be found in the examples directory of this repository.

  5. Query Prometheus data using the API client

    main

    The api/prometheus package provides a client for the Prometheus HTTP API. Use this to write Go applications that programmatically query time series data from a Prometheus server.

    Warning: The API client is currently in an alpha stage and is considered experimental. Breaking changes may occur without a major version bump.

  6. Create a Prometheus Remote Write API client

    main

    Use the github.com/prometheus/client_golang/exp/api/remote package to build clients for Prometheus remote write APIs (supporting v1 and v2).

    Warning: This is an experimental module with an explicitly unstable API. The API may change or be removed without notice.

    import (
        "github.com/prometheus/client_golang/exp/api/remote"
    )
    
    // ...
    
    remoteAPI, err := remote.NewAPI(
        "https://your-remote-endpoint",
        remote.WithAPIHTTPClient(httpClient),
        remote.WithAPILogger(logger.With("component", "remote_write_api")),
    )
    
    // ...
    
    stats, err := remoteAPI.Write(ctx, remote.WriteV2MessageType, protoWriteReq)
  7. Locate model, extraction, and text packages

    main

    If you are looking for the following packages, they have been moved to the prometheus/common repository:

    • model: Now located at prometheus/common/model.
    • extraction and text: Now located at prometheus/common/expfmt.
  8. Initialize a Prometheus API Client with NewClient

    main

    Use NewClient to create a new Client instance for interacting with the Prometheus HTTP API. The client is safe for concurrent use across multiple goroutines. You must provide a Config object containing the Address of your Prometheus server.

    Note that Config.Client and Config.RoundTripper are mutually exclusive; you should provide one or the other, but not both.

  9. Execute HTTP requests with Client.Do

    main

    The Do method executes an HTTP request against the Prometheus API. It handles reading the response body into a byte slice and respects the provided context.Context for cancellation or timeouts.

    Signature: Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error)

    Returns:

    • *http.Response: The HTTP response.
    • []byte: The response body as a byte slice.
    • error: Any error encountered during the request or while reading the body.
  10. Construct API URLs with Client.URL

    main

    The URL method constructs a full *url.URL for a specific endpoint, allowing for path parameter substitution.

    Signature: URL(ep string, args map[string]string) *url.URL

    Parameters:

    • ep: The endpoint path string. This path is joined with the client's base address.
    • args: A map of key-value pairs used to replace placeholders in the endpoint path. Placeholders in the ep string must be prefixed with a colon (e.g., :id).
  11. Use DefaultRoundTripper for standard HTTP settings

    main

    If no RoundTripper is specified in api.Config, the client uses DefaultRoundTripper. This is a pre-configured *http.Transport with the following settings:

    • Proxy: http.ProxyFromEnvironment
    • DialContext Timeout: 30s
    • KeepAlive: 30s
    • ForceAttemptHTTP2: true
    • MaxIdleConns: 100
    • IdleConnTimeout: 90s
    • TLSHandshakeTimeout: 10s
    • ExpectContinueTimeout: 1s
    var DefaultRoundTripper http.RoundTripper = &http.Transport{
    	Proxy:                 http.ProxyFromEnvironment,
    	DialContext:           (&net.Dialer{
    		Timeout:   30 * time.Second,
    		KeepAlive: 30 * time.Second,
    	}).DialContext,
    	ForceAttemptHTTP2:     true,
    	MaxIdleConns:          100,
    	IdleConnTimeout:       90 * time.Second,
    	TLSHandshakeTimeout:   10 * time.Second,
    	ExpectContinueTimeout: 1 * time.Second,
    }
  12. Configure the api.Config struct

    main

    The Config struct defines how the API client connects to Prometheus:

    • Address: The base URL of the Prometheus server (e.g., http://localhost:9090).
    • Client: An optional *http.Client. If provided, it is used to drive requests. If nil, a new client is created using the RoundTripper.
    • RoundTripper: An optional http.RoundTripper. If provided, it is used to drive requests. If nil, DefaultRoundTripper is used.

    Constraint: Client and RoundTripper cannot both be non-nil.

    type Config struct {
    	Address     string
    	Client      *http.Client
    	RoundTripper http.RoundTripper
    }