forked from awsdocs/aws-doc-sdk-examples
/
CreateCustomMetricv2.go
82 lines (70 loc) · 2.55 KB
/
CreateCustomMetricv2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
// snippet-start:[cloudwatch.go-v2.CreateCustomMetric]
package main
import (
"context"
"flag"
"fmt"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
)
// CWPutMetricDataAPI defines the interface for the PutMetricData function.
// We use this interface to test the function using a mocked service.
type CWPutMetricDataAPI interface {
PutMetricData(ctx context.Context,
params *cloudwatch.PutMetricDataInput,
optFns ...func(*cloudwatch.Options)) (*cloudwatch.PutMetricDataOutput, error)
}
// CreateCustomMetric creates a new Amazon CloudWatch metric in a namespace
// Inputs:
// c is the context of the method call, which includes the Region
// api is the interface that defines the method call
// input defines the input arguments to the service call.
// Output:
// If success, a PutMetricDataOutput object containing the result of the service call and nil
// Otherwise, nil and an error from the call to PutMetricData
func CreateCustomMetric(c context.Context, api CWPutMetricDataAPI, input *cloudwatch.PutMetricDataInput) (*cloudwatch.PutMetricDataOutput, error) {
return api.PutMetricData(c, input)
}
func main() {
namespace := flag.String("n", "", "The namespace for the metric")
metricName := flag.String("m", "", "The name of the metric")
value := flag.Float64("s", 0.0, "The number of seconds for the units")
dimensionName := flag.String("dn", "", "The name of the dimension")
dimensionValue := flag.String("dv", "", "The value of the dimension")
flag.Parse()
if *namespace == "" || *metricName == "" || *dimensionName == "" || *dimensionValue == "" {
fmt.Println("You must supply a namespace, metric name, dimension name, and dimension value")
return
}
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic("configuration error, " + err.Error())
}
client := cloudwatch.NewFromConfig(cfg)
input := &cloudwatch.PutMetricDataInput{
Namespace: namespace,
MetricData: []types.MetricDatum{
{
MetricName: metricName,
Unit: types.StandardUnitSeconds,
Value: value,
Dimensions: []types.Dimension{
{
Name: dimensionName,
Value: dimensionValue,
},
},
},
},
}
_, err = CreateCustomMetric(context.TODO(), client, input)
if err != nil {
fmt.Println()
return
}
fmt.Println("Created a custom metric")
}
// snippet-end:[cloudwatch.go-v2.CreateCustomMetric]