azmetrics

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: MIT Imports: 14 Imported by: 1

README

Azure Monitor Query Metrics client module for Go

Source code | Package (pkg.go.dev) | REST API documentation | Product documentation | Samples

Getting started

Prerequisites
  • Go version 1.18 or higher - Install Go
  • Azure subscription - Create a free account
  • The resource URI of an Azure resource (Storage Account, Key Vault, CosmosDB, etc.) that you plan to monitor
Install the packages

Install the azmetrics and azidentity modules with go get:

go get github.com/Azure/azure-sdk-for-go/sdk/monitor/query/azmetrics
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

The azidentity module is used for client authentication.

Authentication

An authenticated client object is required to execute a query. The examples demonstrate using azidentity.NewDefaultAzureCredential to authenticate; however, the client accepts any azidentity credential. See the azidentity documentation for more information about other credential types.

The clients default to the Azure public cloud. For other cloud configurations, see the cloud package documentation.

Create a client

Example client

Key concepts

Azure Monitor Metrics collects numeric data from monitored resources into a time series database. Metrics are numerical values that are collected at regular intervals and describe some aspect of a system at a particular time. Metrics are lightweight and capable of supporting near real-time scenarios, making them particularly useful for alerting and fast detection of issues.

Metrics data structure

Each set of metric values is a time series with the following characteristics:

  • The time the value was collected
  • The resource associated with the value
  • A namespace that acts like a category for the metric
  • A metric name
  • The value itself
  • Some metrics may have multiple dimensions as described in multi-dimensional metrics. Custom metrics can have up to 10 dimensions.

Examples

Get started with our examples.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client contains the methods for the Metrics group. Don't use this type directly, use a constructor function instead.

func NewClient

func NewClient(endpoint string, credential azcore.TokenCredential, options *ClientOptions) (*Client, error)

NewClient creates a client that accesses Azure Monitor metrics data. Client should be used for performing metrics queries on multiple monitored resources in the same region. A credential with authorization at the subscription level is required when using this client.

endpoint - The regional endpoint to use, for example https://eastus.metrics.monitor.azure.com. The region should match the region of the requested resources. For global resources, the region should be 'global'.

Example
package main

import (
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"

	"github.com/Azure/azure-sdk-for-go/sdk/monitor/query/azmetrics"
)

func main() {
	// The regional endpoint to use. The region should match the region of the requested resources.
	// For global resources, the region should be 'global'
	endpoint := "https://eastus.metrics.monitor.azure.com"

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		//TODO: handle error
	}

	client, err := azmetrics.NewClient(endpoint, cred, nil)
	if err != nil {
		//TODO: handle error
	}
	_ = client
}
Output:

func (*Client) QueryResources

func (client *Client) QueryResources(ctx context.Context, subscriptionID string, metricNamespace string, metricNames []string, resourceIDs ResourceIDList, options *QueryResourcesOptions) (QueryResourcesResponse, error)

QueryResources - Lists the metric values for multiple resources. If the operation fails it returns an *azcore.ResponseError type.

Generated from API version 2024-02-01

  • subscriptionID - The subscription identifier for the resources in this batch.
  • metricNamespace - Metric namespace that contains the requested metric names.
  • metricNames - The names of the metrics (comma separated) to retrieve.
  • resourceIDs - Metrics batch body including the list of resource ids
  • options - QueryResourcesOptions contains the optional parameters for the Client.QueryResources method.
Example
// This sample uses the Client to retrieve the "Ingress"
// metric along with the "Average" aggregation type for multiple resources.
// The query will execute over a timespan of 2 hours with a interval (granularity) of 5 minutes.

// In this example, storage account resource URIs are queried for metrics.
resourceURI1 := "/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-1>"
resourceURI2 := "/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-2>"

res, err := client.QueryResources(
	context.Background(),
	subscriptionID,
	"Microsoft.Storage/storageAccounts",
	[]string{"Ingress"},
	azmetrics.ResourceIDList{ResourceIDs: []string{resourceURI1, resourceURI2}},
	&azmetrics.QueryResourcesOptions{
		Aggregation: to.Ptr("average"),
		StartTime:   to.Ptr("2023-11-15"),
		EndTime:     to.Ptr("2023-11-16"),
		Interval:    to.Ptr("PT5M"),
	},
)
if err != nil {
	//TODO: handle error
}

// Print out results
for _, result := range res.Values {
	for _, metric := range result.Values {
		fmt.Println(*metric.Name.Value + ": " + *metric.DisplayDescription)
		for _, timeSeriesElement := range metric.TimeSeries {
			for _, metricValue := range timeSeriesElement.Data {
				fmt.Printf("The ingress at %v is %v.\n", metricValue.TimeStamp.String(), *metricValue.Average)
			}
		}
	}
}
Output:

type ClientOptions

type ClientOptions struct {
	azcore.ClientOptions
}

ClientOptions contains optional settings for Client.

type LocalizableString

type LocalizableString struct {
	// REQUIRED; The invariant value.
	Value *string

	// The display name.
	LocalizedValue *string
}

LocalizableString - The localizable string class.

func (LocalizableString) MarshalJSON

func (l LocalizableString) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type LocalizableString.

func (*LocalizableString) UnmarshalJSON

func (l *LocalizableString) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type LocalizableString.

type MetadataValue

type MetadataValue struct {
	// The name of the metadata.
	Name *LocalizableString

	// The value of the metadata.
	Value *string
}

MetadataValue - Represents a metric metadata value.

func (MetadataValue) MarshalJSON

func (m MetadataValue) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type MetadataValue.

func (*MetadataValue) UnmarshalJSON

func (m *MetadataValue) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type MetadataValue.

type Metric

type Metric struct {
	// REQUIRED; The metric Id.
	ID *string

	// REQUIRED; The name and the display name of the metric, i.e. it is localizable string.
	Name *LocalizableString

	// REQUIRED; The time series returned when a data query is performed.
	TimeSeries []TimeSeriesElement

	// REQUIRED; The resource type of the metric resource.
	Type *string

	// REQUIRED; The unit of the metric.
	Unit *MetricUnit

	// Detailed description of this metric.
	DisplayDescription *string

	// 'Success' or the error details on query failures for this metric.
	ErrorCode *string

	// Error message encountered querying this specific metric.
	ErrorMessage *string
}

Metric - The result data of a query.

func (Metric) MarshalJSON

func (m Metric) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type Metric.

func (*Metric) UnmarshalJSON

func (m *Metric) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type Metric.

type MetricData added in v1.0.0

type MetricData struct {
	// REQUIRED; The end time, in datetime format, for which the data was retrieved.
	EndTime *string

	// REQUIRED; The start time, in datetime format, for which the data was retrieved.
	StartTime *string

	// REQUIRED; The value of the collection.
	Values []Metric

	// The interval (window size) for which the metric data was returned in ISO 8601 duration format with a special case for 'FULL'
	// value that returns single datapoint for entire time span requested (
	// Examples: PT15M, PT1H, P1D, FULL). This may be adjusted and different from what was originally requested if AutoAdjustTimegrain=true
	// is specified.
	Interval *string

	// The namespace of the metrics been queried
	Namespace *string

	// The resource that has been queried for metrics.
	ResourceID *string

	// The region of the resource been queried for metrics.
	ResourceRegion *string
}

MetricData - Metric data values.

func (MetricData) MarshalJSON added in v1.0.0

func (m MetricData) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type MetricData.

func (*MetricData) UnmarshalJSON added in v1.0.0

func (m *MetricData) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type MetricData.

type MetricResults

type MetricResults struct {
	// The collection of metric data responses per resource, per metric.
	Values []MetricData
}

MetricResults - The metrics result for a resource.

func (MetricResults) MarshalJSON

func (m MetricResults) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type MetricResults.

func (*MetricResults) UnmarshalJSON

func (m *MetricResults) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type MetricResults.

type MetricUnit

type MetricUnit string

MetricUnit - The unit of the metric.

const (
	// MetricUnitBitsPerSecond - Rate unit of binary digits per second.
	MetricUnitBitsPerSecond MetricUnit = "BitsPerSecond"
	// MetricUnitByteSeconds - Unit of data transfer or storage. It is the size of the data in bytes multiplied by the time it
	// takes to transfer or store the data in seconds.
	MetricUnitByteSeconds MetricUnit = "ByteSeconds"
	// MetricUnitBytes - Unit of memory in bytes.
	MetricUnitBytes MetricUnit = "Bytes"
	// MetricUnitBytesPerSecond - Rate unit of memory in bytes per second.
	MetricUnitBytesPerSecond MetricUnit = "BytesPerSecond"
	// MetricUnitCores - Unit of processing power.
	MetricUnitCores MetricUnit = "Cores"
	// MetricUnitCount - Unit of raw quantity.
	MetricUnitCount MetricUnit = "Count"
	// MetricUnitCountPerSecond - Rate unit of raw quantity per second.
	MetricUnitCountPerSecond MetricUnit = "CountPerSecond"
	// MetricUnitMilliCores - Unit of processing power in 1/1000th of a CPU core.
	MetricUnitMilliCores MetricUnit = "MilliCores"
	// MetricUnitMilliSeconds - Unit of time in 1/1000th of a second.
	MetricUnitMilliSeconds MetricUnit = "MilliSeconds"
	// MetricUnitNanoCores - Unit of processing power in one billionth of a CPU core.
	MetricUnitNanoCores MetricUnit = "NanoCores"
	// MetricUnitPercent - Percentage unit.
	MetricUnitPercent MetricUnit = "Percent"
	// MetricUnitSeconds - Unit of time in seconds.
	MetricUnitSeconds MetricUnit = "Seconds"
	// MetricUnitUnspecified - No specified unit.
	MetricUnitUnspecified MetricUnit = "Unspecified"
)

func PossibleMetricUnitValues

func PossibleMetricUnitValues() []MetricUnit

PossibleMetricUnitValues returns the possible values for the MetricUnit const type.

type MetricValue

type MetricValue struct {
	// REQUIRED; The timestamp for the metric value in ISO 8601 format.
	TimeStamp *time.Time

	// The average value in the time range.
	Average *float64

	// The number of samples in the time range. Can be used to determine the number of values that contributed to the average
	// value.
	Count *float64

	// The greatest value in the time range.
	Maximum *float64

	// The least value in the time range.
	Minimum *float64

	// The sum of all of the values in the time range.
	Total *float64
}

MetricValue - Represents a metric value.

func (MetricValue) MarshalJSON

func (m MetricValue) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type MetricValue.

func (*MetricValue) UnmarshalJSON

func (m *MetricValue) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type MetricValue.

type QueryResourcesOptions

type QueryResourcesOptions struct {
	// The list of aggregation types (comma separated) to retrieve.Examples: average, minimum, maximum
	Aggregation *string

	// The end time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'.
	EndTime *string

	// The filter is used to reduce the set of metric data returned.
	// Example:
	// Metric contains metadata A, B and C.
	// - Return all time series of C where A = a1 and B = b1 or b2
	// filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘’
	// - Invalid variant:
	// filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘’ or B = ‘b2’
	// This is invalid because the logical or operator cannot separate two different metadata names.
	// - Return all time series where A = a1, B = b1 and C = c1:
	// filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’
	// - Return all time series where A = a1
	// filter=A eq ‘a1’ and B eq ‘’ and C eq ‘’.
	Filter *string

	// The interval (i.e. timegrain) of the query in ISO 8601 duration format. Defaults to PT1M. Special case for 'FULL' value
	// that returns single datapoint for entire time span requested.Examples: PT15M,
	// PT1H, P1D, FULL
	Interval *string

	// The aggregation to use for sorting results and the direction of the sort. Only one order can be specified.Examples: sum
	// asc
	OrderBy *string

	// Dimension name(s) to rollup results by. For example if you only want to see metric values with a filter like 'City eq Seattle
	// or City eq Tacoma' but don't want to see separate values for each city,
	// you can specify 'RollUpBy=City' to see the results for Seattle and Tacoma rolled up into one timeseries.
	RollUpBy *string

	// The start time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'. If you have specified the endtime
	// parameter, then this parameter is required. If only starttime is specified, then
	// endtime defaults to the current time. If no time interval is specified, the default is 1 hour.
	StartTime *string

	// The maximum number of records to retrieve per resource ID in the request. Valid only if filter is specified. Defaults to
	// 10.
	Top *int32
}

QueryResourcesOptions contains the optional parameters for the Client.QueryResources method.

type QueryResourcesResponse

type QueryResourcesResponse struct {
	// The metrics result for a resource.
	MetricResults
}

QueryResourcesResponse contains the response from method Client.QueryResources.

type ResourceIDList

type ResourceIDList struct {
	// The list of resource IDs to query metrics for.
	ResourceIDs []string
}

ResourceIDList - The comma separated list of resource IDs to query metrics for.

func (ResourceIDList) MarshalJSON

func (r ResourceIDList) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type ResourceIDList.

func (*ResourceIDList) UnmarshalJSON

func (r *ResourceIDList) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type ResourceIDList.

type TimeSeriesElement

type TimeSeriesElement struct {
	// An array of data points representing the metric values. This is only returned if a result type of data is specified.
	Data []MetricValue

	// The metadata values returned if $filter was specified in the call.
	MetadataValues []MetadataValue
}

TimeSeriesElement - A time series result type. The discriminator value is always TimeSeries in this case.

func (TimeSeriesElement) MarshalJSON

func (t TimeSeriesElement) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface for type TimeSeriesElement.

func (*TimeSeriesElement) UnmarshalJSON

func (t *TimeSeriesElement) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaller interface for type TimeSeriesElement.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL