Implementing custom telemetry using AWS CloudWatch SDK.

Hello Friends, Today we will be creating custom telemetry using AWS Cloudwatch SDK. This will use Cloudwatch to store the data. To understand more about Cloudwatch metrics please visit this LINK.

Prerequisites:

Now that we know what we are doing let's start the implementation.

package mainimport (
"math/rand"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"fmt"
)
func main() {
// Initialize a session that the SDK uses to load
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: aws.Config{
// ...
Region: aws.String("<MY_REGION>"),
Credentials: credentials.NewStaticCredentials(
"MY_ACCESS_KEY",
"MY_SECRET_KEY",
"",
),
},
}))
// Create new cloudwatch client.
svc := cloudwatch.New(sess)
_, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{
Namespace: aws.String("MyAppTelemetry"),
MetricData: []*cloudwatch.MetricDatum{
&cloudwatch.MetricDatum{
MetricName: aws.String("CustomMetric"),
Unit: aws.String("Count"),
Value: aws.Float64(rand.Float64() * 10),
Dimensions: []*cloudwatch.Dimension{
&cloudwatch.Dimension{
Name: aws.String("mymobileapp"),
Value: aws.String("abc.xyz"),
},
},
},
},
})
if err != nil {
fmt.Println("Error adding metrics:", err.Error())
return
}
// Get information about metrics
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
Namespace: aws.String("MyAppTelemetry"),
})
if err != nil {
fmt.Println("Error getting metrics:", err.Error())
return
}
for _, metric := range result.Metrics {
fmt.Println(*metric.MetricName)
for _, dim := range metric.Dimensions {
fmt.Println(*dim.Name+":", *dim.Value)
fmt.Println()
}
}
}
go run main.go

if you got no error that means the application execution was successful and data values are being sent to Cloudwatch.

Thanks for reading. I hope this story was helpful. If you are interested,

check out my other articles.

you can also visit shubhamdeshmukh.com.

Comments

Popular posts from this blog

Loki, Grafana, and Promtail integration using Docker

Getting Started | Infrastructure as Code(IaC) with examples.

Monitoring multiple federated instances with Prometheus