Skip to content

Instantly share code, notes, and snippets.

@vatshat
Last active August 6, 2019 18:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vatshat/ca2e3c8ebb05d403eb1d2354587ba8c0 to your computer and use it in GitHub Desktop.
Save vatshat/ca2e3c8ebb05d403eb1d2354587ba8c0 to your computer and use it in GitHub Desktop.
FilterLogEvents and ListMetrics example in Go
package main
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
func main() {
filterLogEvents()
//listMetrics()
}
// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/sessions.html
func filterLogEvents() {
/*
not sure how you configured your context object, so I used the default provided in our documentation
https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-requests-with-go-sdk.html#using-context-context-with-requests
*/
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
/*
startTimeMs := aws.TimeUnixMilli(
time.Date(2018, 12, 10, 13, 00, 00, 0, time.UTC),
)
*/
startTimeMs := aws.TimeUnixMilli(
time.Now().Add(-time.Hour),
)
logLevel := aws.LogDebugWithRequestRetries
result, err := cwLogsAPI(&logLevel).FilterLogEventsWithContext(ctx, &cloudwatchlogs.FilterLogEventsInput{
Interleaved: aws.Bool(true),
LogGroupName: aws.String("CloudTrail/DefaultLogGroup"),
StartTime: &startTimeMs,
})
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Logs", result.Events)
}
func listMetrics() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
// Create CloudWatch client
svc := cloudwatch.New(
sess,
aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody),
)
// List metrics
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
MetricName: aws.String("IncomingLogEvents"),
Namespace: aws.String("AWS/Logs"),
Dimensions: []*cloudwatch.DimensionFilter{
&cloudwatch.DimensionFilter{
Name: aws.String("LogGroupName"),
},
},
})
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Metrics", result.Metrics)
}
func cwLogsAPI(logLevelType *aws.LogLevelType) *cloudwatchlogs.CloudWatchLogs {
return cloudwatchlogs.New(
session.Must(session.NewSession()),
&aws.Config{
LogLevel: logLevelType,
Retryer: client.DefaultRetryer{NumMaxRetries: 10},
},
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment