Movatterモバイル変換


[0]ホーム

URL:


v1

package
v1.23.2Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 5, 2025 License:Apache-2.0Imports:13Imported by:1,389

Details

Repository

github.com/prometheus/client_golang

Links

Documentation

Overview

Package v1 provides bindings to the Prometheus HTTP API v1:http://prometheus.io/docs/querying/api/

Index

Examples

Constants

View Source
const (// Possible values for AlertState.AlertStateFiringAlertState = "firing"AlertStateInactiveAlertState = "inactive"AlertStatePendingAlertState = "pending"// Possible values for ErrorType.ErrBadDataErrorType = "bad_data"ErrTimeoutErrorType = "timeout"ErrCanceledErrorType = "canceled"ErrExecErrorType = "execution"ErrBadResponseErrorType = "bad_response"ErrServerErrorType = "server_error"ErrClientErrorType = "client_error"// Possible values for HealthStatus.HealthGoodHealthStatus = "up"HealthUnknownHealthStatus = "unknown"HealthBadHealthStatus = "down"// Possible values for RuleType.RuleTypeRecordingRuleType = "recording"RuleTypeAlertingRuleType = "alerting"// Possible values for RuleHealth.RuleHealthGood    = "ok"RuleHealthUnknown = "unknown"RuleHealthBad     = "err"// Possible values for MetricTypeMetricTypeCounterMetricType = "counter"MetricTypeGaugeMetricType = "gauge"MetricTypeHistogramMetricType = "histogram"MetricTypeGaugeHistogramMetricType = "gaugehistogram"MetricTypeSummaryMetricType = "summary"MetricTypeInfoMetricType = "info"MetricTypeStatesetMetricType = "stateset"MetricTypeUnknownMetricType = "unknown")

Variables

This section is empty.

Functions

This section is empty.

Types

typeAPI

type API interface {// Alerts returns a list of all active alerts.Alerts(ctxcontext.Context) (AlertsResult,error)// AlertManagers returns an overview of the current state of the Prometheus alert manager discovery.AlertManagers(ctxcontext.Context) (AlertManagersResult,error)// CleanTombstones removes the deleted data from disk and cleans up the existing tombstones.CleanTombstones(ctxcontext.Context)error// Config returns the current Prometheus configuration.Config(ctxcontext.Context) (ConfigResult,error)// DeleteSeries deletes data for a selection of series in a time range.DeleteSeries(ctxcontext.Context, matches []string, startTime, endTimetime.Time)error// Flags returns the flag values that Prometheus was launched with.Flags(ctxcontext.Context) (FlagsResult,error)// LabelNames returns the unique label names present in the block in sorted order by given time range and matchers.LabelNames(ctxcontext.Context, matches []string, startTime, endTimetime.Time, opts ...Option) ([]string,Warnings,error)// LabelValues performs a query for the values of the given label, time range and matchers.LabelValues(ctxcontext.Context, labelstring, matches []string, startTime, endTimetime.Time, opts ...Option) (model.LabelValues,Warnings,error)// Query performs a query for the given time.Query(ctxcontext.Context, querystring, tstime.Time, opts ...Option) (model.Value,Warnings,error)// QueryRange performs a query for the given range.QueryRange(ctxcontext.Context, querystring, rRange, opts ...Option) (model.Value,Warnings,error)// QueryExemplars performs a query for exemplars by the given query and time range.QueryExemplars(ctxcontext.Context, querystring, startTime, endTimetime.Time) ([]ExemplarQueryResult,error)// Buildinfo returns various build information properties about the Prometheus serverBuildinfo(ctxcontext.Context) (BuildinfoResult,error)// Runtimeinfo returns the various runtime information properties about the Prometheus server.Runtimeinfo(ctxcontext.Context) (RuntimeinfoResult,error)// Series finds series by label matchers.Series(ctxcontext.Context, matches []string, startTime, endTimetime.Time, opts ...Option) ([]model.LabelSet,Warnings,error)// Snapshot creates a snapshot of all current data into snapshots/<datetime>-<rand>// under the TSDB's data directory and returns the directory as response.Snapshot(ctxcontext.Context, skipHeadbool) (SnapshotResult,error)// Rules returns a list of alerting and recording rules that are currently loaded.Rules(ctxcontext.Context) (RulesResult,error)// Targets returns an overview of the current state of the Prometheus target discovery.Targets(ctxcontext.Context) (TargetsResult,error)// TargetsMetadata returns metadata about metrics currently scraped by the target.TargetsMetadata(ctxcontext.Context, matchTarget, metric, limitstring) ([]MetricMetadata,error)// Metadata returns metadata about metrics currently scraped by the metric name.Metadata(ctxcontext.Context, metric, limitstring) (map[string][]Metadata,error)// TSDB returns the cardinality statistics.TSDB(ctxcontext.Context, opts ...Option) (TSDBResult,error)// WalReplay returns the current replay status of the wal.WalReplay(ctxcontext.Context) (WalReplayStatus,error)}

API provides bindings for Prometheus's v1 API.

Example (Query)
package mainimport ("context""fmt""os""time""github.com/prometheus/client_golang/api"v1 "github.com/prometheus/client_golang/api/prometheus/v1")const DemoPrometheusURL = "https://demo.prometheus.io:443"func main() {client, err := api.NewClient(api.Config{Address: DemoPrometheusURL,})if err != nil {fmt.Printf("Error creating client: %v\n", err)os.Exit(1)}v1api := v1.NewAPI(client)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()result, warnings, err := v1api.Query(ctx, "up", time.Now(), v1.WithTimeout(5*time.Second))if err != nil {fmt.Printf("Error querying Prometheus: %v\n", err)os.Exit(1)}if len(warnings) > 0 {fmt.Printf("Warnings: %v\n", warnings)}fmt.Printf("Result:\n%v\n", result)}

Example (QueryRange)
package mainimport ("context""fmt""os""time""github.com/prometheus/client_golang/api"v1 "github.com/prometheus/client_golang/api/prometheus/v1")const DemoPrometheusURL = "https://demo.prometheus.io:443"func main() {client, err := api.NewClient(api.Config{Address: DemoPrometheusURL,})if err != nil {fmt.Printf("Error creating client: %v\n", err)os.Exit(1)}v1api := v1.NewAPI(client)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()r := v1.Range{Start: time.Now().Add(-time.Hour),End:   time.Now(),Step:  time.Minute,}result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, v1.WithTimeout(5*time.Second))if err != nil {fmt.Printf("Error querying Prometheus: %v\n", err)os.Exit(1)}if len(warnings) > 0 {fmt.Printf("Warnings: %v\n", warnings)}fmt.Printf("Result:\n%v\n", result)}

Example (QueryRangeWithAuthBearerToken)
package mainimport ("context""fmt""os""time""github.com/prometheus/common/config""github.com/prometheus/client_golang/api"v1 "github.com/prometheus/client_golang/api/prometheus/v1")const DemoPrometheusURL = "https://demo.prometheus.io:443"func main() {client, err := api.NewClient(api.Config{Address: DemoPrometheusURL,// We can use amazing github.com/prometheus/common/config helper!RoundTripper: config.NewAuthorizationCredentialsRoundTripper("Bearer",config.NewInlineSecret("secret_token"),api.DefaultRoundTripper,),})if err != nil {fmt.Printf("Error creating client: %v\n", err)os.Exit(1)}v1api := v1.NewAPI(client)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()r := v1.Range{Start: time.Now().Add(-time.Hour),End:   time.Now(),Step:  time.Minute,}result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)if err != nil {fmt.Printf("Error querying Prometheus: %v\n", err)os.Exit(1)}if len(warnings) > 0 {fmt.Printf("Warnings: %v\n", warnings)}fmt.Printf("Result:\n%v\n", result)}

Example (QueryRangeWithAuthBearerTokenHeadersRoundTripper)
package mainimport ("context""fmt""os""time""github.com/prometheus/common/config""github.com/prometheus/client_golang/api"v1 "github.com/prometheus/client_golang/api/prometheus/v1")const DemoPrometheusURL = "https://demo.prometheus.io:443"func main() {client, err := api.NewClient(api.Config{Address: DemoPrometheusURL,// We can use amazing github.com/prometheus/common/config helper!RoundTripper: config.NewHeadersRoundTripper(&config.Headers{Headers: map[string]config.Header{"Authorization": {Values: []string{"Bearer secret"},},},},api.DefaultRoundTripper,),})if err != nil {fmt.Printf("Error creating client: %v\n", err)os.Exit(1)}v1api := v1.NewAPI(client)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()r := v1.Range{Start: time.Now().Add(-time.Hour),End:   time.Now(),Step:  time.Minute,}result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)if err != nil {fmt.Printf("Error querying Prometheus: %v\n", err)os.Exit(1)}if len(warnings) > 0 {fmt.Printf("Warnings: %v\n", warnings)}fmt.Printf("Result:\n%v\n", result)}

Example (QueryRangeWithBasicAuth)
package mainimport ("context""fmt""os""time""github.com/prometheus/common/config""github.com/prometheus/client_golang/api"v1 "github.com/prometheus/client_golang/api/prometheus/v1")const DemoPrometheusURL = "https://demo.prometheus.io:443"func main() {client, err := api.NewClient(api.Config{Address: DemoPrometheusURL,// We can use amazing github.com/prometheus/common/config helper!RoundTripper: config.NewBasicAuthRoundTripper(config.NewInlineSecret("me"),config.NewInlineSecret("definitely_me"),api.DefaultRoundTripper,),})if err != nil {fmt.Printf("Error creating client: %v\n", err)os.Exit(1)}v1api := v1.NewAPI(client)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()r := v1.Range{Start: time.Now().Add(-time.Hour),End:   time.Now(),Step:  time.Minute,}result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)if err != nil {fmt.Printf("Error querying Prometheus: %v\n", err)os.Exit(1)}if len(warnings) > 0 {fmt.Printf("Warnings: %v\n", warnings)}fmt.Printf("Result:\n%v\n", result)}

Example (QueryRangeWithUserAgent)
package mainimport ("context""fmt""net/http""os""time""github.com/prometheus/client_golang/api"v1 "github.com/prometheus/client_golang/api/prometheus/v1")const DemoPrometheusURL = "https://demo.prometheus.io:443"type userAgentRoundTripper struct {name stringrt   http.RoundTripper}// RoundTrip implements the http.RoundTripper interface.func (u userAgentRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {if r.UserAgent() == "" {r2 := new(http.Request)*r2 = *rr2.Header = make(http.Header)for k, s := range r.Header {r2.Header[k] = s}r2.Header.Set("User-Agent", u.name)r = r2}return u.rt.RoundTrip(r)}func main() {client, err := api.NewClient(api.Config{Address:      DemoPrometheusURL,RoundTripper: userAgentRoundTripper{name: "Client-Golang", rt: api.DefaultRoundTripper},})if err != nil {fmt.Printf("Error creating client: %v\n", err)os.Exit(1)}v1api := v1.NewAPI(client)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()r := v1.Range{Start: time.Now().Add(-time.Hour),End:   time.Now(),Step:  time.Minute,}result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)if err != nil {fmt.Printf("Error querying Prometheus: %v\n", err)os.Exit(1)}if len(warnings) > 0 {fmt.Printf("Warnings: %v\n", warnings)}fmt.Printf("Result:\n%v\n", result)}

Example (Series)
package mainimport ("context""fmt""os""time""github.com/prometheus/client_golang/api"v1 "github.com/prometheus/client_golang/api/prometheus/v1")const DemoPrometheusURL = "https://demo.prometheus.io:443"func main() {client, err := api.NewClient(api.Config{Address: DemoPrometheusURL,})if err != nil {fmt.Printf("Error creating client: %v\n", err)os.Exit(1)}v1api := v1.NewAPI(client)ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()lbls, warnings, err := v1api.Series(ctx, []string{"{__name__=~\"scrape_.+\",job=\"node\"}","{__name__=~\"scrape_.+\",job=\"prometheus\"}",}, time.Now().Add(-time.Hour), time.Now())if err != nil {fmt.Printf("Error querying Prometheus: %v\n", err)os.Exit(1)}if len(warnings) > 0 {fmt.Printf("Warnings: %v\n", warnings)}fmt.Println("Result:")for _, lbl := range lbls {fmt.Println(lbl)}}

funcNewAPI

func NewAPI(capi.Client)API

NewAPI returns a new API for the client.

It is safe to use the returned API from multiple goroutines.

typeActiveTarget

type ActiveTarget struct {DiscoveredLabels   map[string]string `json:"discoveredLabels"`Labelsmodel.LabelSet    `json:"labels"`ScrapePoolstring            `json:"scrapePool"`ScrapeURLstring            `json:"scrapeUrl"`GlobalURLstring            `json:"globalUrl"`LastErrorstring            `json:"lastError"`LastScrapetime.Time         `json:"lastScrape"`LastScrapeDurationfloat64           `json:"lastScrapeDuration"`HealthHealthStatus      `json:"health"`}

ActiveTarget models an active Prometheus scrape target.

typeAlertadded inv0.9.3

type Alert struct {ActiveAttime.Time `json:"activeAt"`Annotationsmodel.LabelSetLabelsmodel.LabelSetStateAlertStateValuestring}

Alert models an active alert.

typeAlertManager

type AlertManager struct {URLstring `json:"url"`}

AlertManager models a configured Alert Manager.

typeAlertManagersResult

type AlertManagersResult struct {Active  []AlertManager `json:"activeAlertManagers"`Dropped []AlertManager `json:"droppedAlertManagers"`}

AlertManagersResult contains the result from querying the alertmanagers endpoint.

typeAlertStateadded inv0.9.3

type AlertStatestring

AlertState models the state of an alert.

typeAlertingRuleadded inv0.9.3

type AlertingRule struct {Namestring         `json:"name"`Querystring         `json:"query"`Durationfloat64        `json:"duration"`Labelsmodel.LabelSet `json:"labels"`Annotationsmodel.LabelSet `json:"annotations"`Alerts         []*Alert       `json:"alerts"`HealthRuleHealth     `json:"health"`LastErrorstring         `json:"lastError,omitempty"`EvaluationTimefloat64        `json:"evaluationTime"`LastEvaluationtime.Time      `json:"lastEvaluation"`Statestring         `json:"state"`}

AlertingRule models a alerting rule.

func (*AlertingRule)UnmarshalJSONadded inv0.9.3

func (r *AlertingRule) UnmarshalJSON(b []byte)error

typeAlertsResultadded inv0.9.3

type AlertsResult struct {Alerts []Alert `json:"alerts"`}

AlertsResult contains the result from querying the alerts endpoint.

typeBuildinfoResultadded inv0.12.1

type BuildinfoResult struct {Versionstring `json:"version"`Revisionstring `json:"revision"`Branchstring `json:"branch"`BuildUserstring `json:"buildUser"`BuildDatestring `json:"buildDate"`GoVersionstring `json:"goVersion"`}

BuildinfoResult contains the results from querying the buildinfo endpoint.

typeConfigResult

type ConfigResult struct {YAMLstring `json:"yaml"`}

ConfigResult contains the result from querying the config endpoint.

typeDroppedTarget

type DroppedTarget struct {DiscoveredLabels map[string]string `json:"discoveredLabels"`}

DroppedTarget models a dropped Prometheus scrape target.

typeError

type Error struct {TypeErrorTypeMsgstringDetailstring}

Error is an error returned by the API.

func (*Error)Error

func (e *Error) Error()string

typeErrorType

type ErrorTypestring

ErrorType models the different API error types.

typeExemplaradded inv0.12.1

type Exemplar struct {Labelsmodel.LabelSet    `json:"labels"`Valuemodel.SampleValue `json:"value"`Timestampmodel.Time        `json:"timestamp"`}

Exemplar is additional information associated with a time series.

typeExemplarQueryResultadded inv0.12.1

type ExemplarQueryResult struct {SeriesLabelsmodel.LabelSet `json:"seriesLabels"`Exemplars    []Exemplar     `json:"exemplars"`}

typeFlagsResult

type FlagsResult map[string]string

FlagsResult contains the result from querying the flag endpoint.

typeHealthStatus

type HealthStatusstring

HealthStatus models the health status of a scrape target.

typeMetadataadded inv0.12.1

type Metadata struct {TypeMetricType `json:"type"`Helpstring     `json:"help"`Unitstring     `json:"unit"`}

Metadata models the metadata of a metric.

typeMetricMetadataadded inv0.9.4

type MetricMetadata struct {Target map[string]string `json:"target"`Metricstring            `json:"metric,omitempty"`TypeMetricType        `json:"type"`Helpstring            `json:"help"`Unitstring            `json:"unit"`}

MetricMetadata models the metadata of a metric with its scrape target and name.

typeMetricTypeadded inv0.9.4

type MetricTypestring

MetricType models the type of a metric.

typeOptionadded inv1.13.0

type Option func(c *apiOptions)

funcWithLimitadded inv1.20.0

func WithLimit(limituint64)Option

WithLimit provides an optional maximum number of returned entries for APIs that support limit parametere.g.https://prometheus.io/docs/prometheus/latest/querying/api/#instant-querie:~:text=%3A%20End%20timestamp.-,limit%3D%3Cnumber%3E,-%3A%20Maximum%20number%20of

funcWithLookbackDeltaadded inv1.22.0

func WithLookbackDelta(lookbackDeltatime.Duration)Option

WithLookbackDelta can be used to provide an optional query lookback delta for Query and QueryRange.This URL variable is not documented on Prometheus HTTP API.https://github.com/prometheus/prometheus/blob/e04913aea2792a5c8bc7b3130c389ca1b027dd9b/promql/engine.go#L162-L167

funcWithStatsadded inv1.22.0

func WithStats(statsStatsValue)Option

WithStats can be used to provide an optional per step stats for Query and QueryRange.This URL variable is not documented on Prometheus HTTP API.https://github.com/prometheus/prometheus/blob/e04913aea2792a5c8bc7b3130c389ca1b027dd9b/promql/engine.go#L162-L167

funcWithTimeoutadded inv1.13.0

func WithTimeout(timeouttime.Duration)Option

WithTimeout can be used to provide an optional query evaluation timeout for Query and QueryRange.https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries

typeRange

type Range struct {// The boundaries of the time range.Start, Endtime.Time// The maximum time between two slices within the boundaries.Steptime.Duration}

Range represents a sliced time range.

typeRecordingRuleadded inv0.9.3

type RecordingRule struct {Namestring         `json:"name"`Querystring         `json:"query"`Labelsmodel.LabelSet `json:"labels,omitempty"`HealthRuleHealth     `json:"health"`LastErrorstring         `json:"lastError,omitempty"`EvaluationTimefloat64        `json:"evaluationTime"`LastEvaluationtime.Time      `json:"lastEvaluation"`}

RecordingRule models a recording rule.

func (*RecordingRule)UnmarshalJSONadded inv0.9.3

func (r *RecordingRule) UnmarshalJSON(b []byte)error

typeRuleGroupadded inv0.9.3

type RuleGroup struct {Namestring  `json:"name"`Filestring  `json:"file"`Intervalfloat64 `json:"interval"`RulesRules   `json:"rules"`}

RuleGroup models a rule group that contains a set of recording and alerting rules.

func (*RuleGroup)UnmarshalJSONadded inv0.9.3

func (rg *RuleGroup) UnmarshalJSON(b []byte)error

typeRuleHealthadded inv0.9.3

type RuleHealthstring

RuleHealth models the health status of a rule.

typeRuleTypeadded inv0.9.3

type RuleTypestring

RuleType models the type of a rule.

typeRulesadded inv0.9.3

type Rules []interface{}

Recording and alerting rules are stored in the same slice to preserve the orderthat rules are returned in by the API.

Rule types can be determined using a type switch:

switch v := rule.(type) {case RecordingRule:fmt.Print("got a recording rule")case AlertingRule:fmt.Print("got a alerting rule")default:fmt.Printf("unknown rule type %s", v)}

typeRulesResultadded inv0.9.3

type RulesResult struct {Groups []RuleGroup `json:"groups"`}

RulesResult contains the result from querying the rules endpoint.

typeRuntimeinfoResultadded inv0.12.1

type RuntimeinfoResult struct {StartTimetime.Time `json:"startTime"`CWDstring    `json:"CWD"`ReloadConfigSuccessbool      `json:"reloadConfigSuccess"`LastConfigTimetime.Time `json:"lastConfigTime"`CorruptionCountint       `json:"corruptionCount"`GoroutineCountint       `json:"goroutineCount"`GOMAXPROCSint       `json:"GOMAXPROCS"`GOGCstring    `json:"GOGC"`GODEBUGstring    `json:"GODEBUG"`StorageRetentionstring    `json:"storageRetention"`}

RuntimeinfoResult contains the result from querying the runtimeinfo endpoint.

typeSnapshotResult

type SnapshotResult struct {Namestring `json:"name"`}

SnapshotResult contains the result from querying the snapshot endpoint.

typeStatadded inv0.12.1

type Stat struct {Namestring `json:"name"`Valueuint64 `json:"value"`}

Stat models information about statistic value.

typeStatsValueadded inv1.22.0

type StatsValuestring

StatsValue is a type for `stats` query parameter.

const (AllStatsValueStatsValue = "all")

AllStatsValue is the query parameter value to return all the query statistics.

typeTSDBHeadStatsadded inv0.12.1

type TSDBHeadStats struct {NumSeriesint `json:"numSeries"`NumLabelPairsint `json:"numLabelPairs"`ChunkCountint `json:"chunkCount"`MinTimeint `json:"minTime"`MaxTimeint `json:"maxTime"`}

TSDBHeadStats contains TSDB stats

typeTSDBResultadded inv0.12.1

type TSDBResult struct {HeadStatsTSDBHeadStats `json:"headStats"`SeriesCountByMetricName     []Stat        `json:"seriesCountByMetricName"`LabelValueCountByLabelName  []Stat        `json:"labelValueCountByLabelName"`MemoryInBytesByLabelName    []Stat        `json:"memoryInBytesByLabelName"`SeriesCountByLabelValuePair []Stat        `json:"seriesCountByLabelValuePair"`}

TSDBResult contains the result from querying the tsdb endpoint.

typeTargetsResult

type TargetsResult struct {Active  []ActiveTarget  `json:"activeTargets"`Dropped []DroppedTarget `json:"droppedTargets"`}

TargetsResult contains the result from querying the targets endpoint.

typeWalReplayStatusadded inv0.12.1

type WalReplayStatus struct {Minint `json:"min"`Maxint `json:"max"`Currentint `json:"current"`}

WalReplayStatus represents the wal replay status.

typeWarningsadded inv0.12.1

type Warnings []string

Warnings is an array of non critical errors

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp