

AWS SDK for Go V1 has reached end-of-support. We recommend that you migrate to [AWS SDK for Go V2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-go-v1-on-july-31-2025/).

# Amazon CloudWatch Examples Using the AWS SDK for Go
Amazon CloudWatch Examples

Amazon CloudWatch is a web service that monitors your AWS resources and the applications you run on AWS in real time. You can use CloudWatch to collect and track metrics, which are variables you can measure for your resources and applications. CloudWatch alarms send notifications or automatically make changes to the resources you are monitoring based on rules that you define.

The AWS SDK for Go examples show you how to integrate CloudWatch into your Go applications. The examples assume you have already set up and configured the SDK (that is, you have imported all required packages and set your credentials and region). For more information, see [Getting Started with the AWS SDK for Go](setting-up.md) and [Configuring the AWS SDK for Go](configuring-sdk.md).

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/cloudwatch) repository on GitHub.

**Topics**
+ [

# Describing CloudWatch Alarms
](cw-example-describing-alarms.md)
+ [

# Using Alarms and Alarm Actions in CloudWatch
](cw-example-using-alarm-actions.md)
+ [

# Getting Metrics from CloudWatch
](cw-example-getting-metrics.md)
+ [

# Sending Events to Amazon CloudWatch Events
](cw-example-sending-events.md)
+ [

# Getting Log Events from CloudWatch
](cw-example-getting-log-events.md)

# Describing CloudWatch Alarms


This example shows you how to retrieve basic information that describes your CloudWatch alarms.

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/cloudwatch) repository on GitHub.

## Scenario


An alarm watches a single metric over a time period you specify. The alarm performs one or more actions based on the value of the metric relative to a given threshold over a number of time periods.

In this example, Go code is used to describe alarms in CloudWatch. The code uses the AWS SDK for Go to describe alarms by using this method of the `AWS.CloudWatch` client class:
+  [DescribeAlarms](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.DescribeAlarms) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch alarms. To learn more, see [Creating Amazon CloudWatch Alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html) in the Amazon CloudWatch User Guide.

## Describe Alarms


Choose **Copy** to save the code locally.

Create the file `describe_alarms.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

svc := cloudwatch.New(sess)
```

Call `DescribeAlarms`, and print the results.

```
resp, err := svc.DescribeAlarms(nil)
for _, alarm := range resp.MetricAlarms {
    fmt.Println(*alarm.AlarmName)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/describe_alarms.go) on GitHub.

# Using Alarms and Alarm Actions in CloudWatch


These Go examples show you how to change the state of your Amazon EC2 instances automatically based on a CloudWatch alarm, as follows:
+ Creating and enabling actions on an alarm
+ Disabling actions on an alarm

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/cloudwatch) repository on GitHub.

## Scenario


You can use alarm actions to create alarms that automatically stop, terminate, reboot, or recover your Amazon EC2 instances. You can use the stop or terminate actions when you no longer need an instance to be running. You can use the reboot and recover actions to automatically reboot the instance.

In this example, Go code is used to define an alarm action in CloudWatch that triggers the reboot of an Amazon EC2 instance. The code uses the AWS SDK for Go to manage instances by using these methods of [PutMetricAlarm](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch) type:
+  [PutMetricAlarm](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.PutMetricAlarm) 
+  [EnableAlarmActions](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.EnableAlarmActions) 
+  [DisableAlarmActions](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.DisableAlarmActions) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch alarm actions. To learn more, see [Create Alarms to Stop, Terminate, Reboot, or Recover an Instance](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html) in the Amazon CloudWatch User Guide.

## Create and Enable Actions on an Alarm


Choose **Copy** to save the code locally.

Create the file `create_enable_alarms.go`.

Import packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Get an instance name, value, and alarm name.

```
if len(os.Args) != 4 {
    fmt.Println("You must supply an instance name, value, and alarm name")
    os.Exit(1)
}

instance := os.Args[1]
value := os.Args[2]
name := os.Args[3]
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create new CloudWatch client.
svc := cloudwatch.New(sess)
```

Create a metric alarm that reboots an instance if its CPU utilization is greater than 70 percent.

```
_, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{
    AlarmName:          aws.String(name),
    ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold),
    EvaluationPeriods:  aws.Int64(1),
    MetricName:         aws.String("CPUUtilization"),
    Namespace:          aws.String("AWS/EC2"),
    Period:             aws.Int64(60),
    Statistic:          aws.String(cloudwatch.StatisticAverage),
    Threshold:          aws.Float64(70.0),
    ActionsEnabled:     aws.Bool(true),
    AlarmDescription:   aws.String("Alarm when server CPU exceeds 70%"),
    Unit:               aws.String(cloudwatch.StandardUnitSeconds),

    // This is apart of the default workflow actions. This one will reboot the instance, if the
    // alarm is triggered.
    AlarmActions: []*string{
        aws.String(fmt.Sprintf("arn:aws:swf:us-east-1:%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", instance)),
    },
    Dimensions: []*cloudwatch.Dimension{
        {
            Name:  aws.String("InstanceId"),
            Value: aws.String(value),
        },
    },
})
```

Call `EnableAlarmActions` with the new alarm for the instance, and display a message.

```
result, err := svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{
    AlarmNames: []*string{
        aws.String(name),
    },
})
fmt.Println("Alarm action enabled", result)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/create_enable_alarms.go) on GitHub.

## Disable Actions on an Alarm


Choose **Copy** to save the code locally.

Create the file `disable_alarm.go`.

Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Get the name of the alarm from the command line.

```
if len(os.Args) != 2 {
    fmt.Println("You must supply an alarm name")
    os.Exit(1)
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create new CloudWatch client.
svc := cloudwatch.New(sess)
```

Call `DisableAlarmActions` to disable the actions for this alarm and display a message.

```
// Disable the alarm.
_, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{
    AlarmNames: []*string{
        aws.String(name),
    },
})
fmt.Println("Success")
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/disable_alarm.go) on GitHub.

# Getting Metrics from CloudWatch


These Go examples show you how to retrieve a list of published CloudWatch metrics and publish data points to CloudWatch metrics with the AWS SDK for Go, as follows:
+ Listing metrics
+ Submitting custom metrics

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/cloudwatch) repository on GitHub.

## Scenario


Metrics are data about the performance of your systems. You can enable detailed monitoring of some resources, such as your Amazon EC2 instances, or your own application metrics.

In this example, Go code is used to get metrics from CloudWatch and to send events to CloudWatch Events. The code uses the AWS SDK for Go to get metrics from CloudWatch by using these methods of the CloudWatch type:
+  [ListMetrics](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.ListMetrics) 
+  [PutMetricData](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.PutMetricData) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch metrics. To learn more, see [Using Amazon CloudWatch Metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) in the Amazon CloudWatch User Guide.

## List Metrics


Choose **Copy** to save the code locally.

Create the file `listing_metrics.go`.

Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Get the metric name, namespace, and dimension name from the command line.

```
if len(os.Args) != 4 {
    fmt.Println("You must supply a metric name, namespace, and dimension name")
    os.Exit(1)
}

metric := os.Args[1]
namespace := os.Args[2]
dimension := os.Args[3]
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create CloudWatch client
svc := cloudwatch.New(sess)
```

Call `ListMetrics`, supplying the metric name, namespace, and dimension name. Print the metrics returned in the result.

```
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
    MetricName: aws.String(metric),
    Namespace:  aws.String(namespace),
    Dimensions: []*cloudwatch.DimensionFilter{
        &cloudwatch.DimensionFilter{
            Name: aws.String(dimension),
        },
    },
})
fmt.Println("Metrics", result.Metrics)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/listing_metrics.go) on GitHub.

## Submit Custom Metrics


Choose **Copy** to save the code locally.

Create the file `custom_metrics.go`.

Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create new cloudwatch client.
svc := cloudwatch.New(sess)
```

Call `PutMetricData` with the the custom namespace “Site/Traffic”. The namespace has two custom dimensions: “SiteName” and “PageURL”. “SiteName” has the value “example.com”, the “UniqueVisitors” value 5885 and the “UniqueVisits” value 8628. “PageURL” has the value “my-page.html”, and a “PageViews” value 18057.

```
_, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{
    Namespace: aws.String("Site/Traffic"),
    MetricData: []*cloudwatch.MetricDatum{
        &cloudwatch.MetricDatum{
            MetricName: aws.String("UniqueVisitors"),
            Unit:       aws.String("Count"),
            Value:      aws.Float64(5885.0),
            Dimensions: []*cloudwatch.Dimension{
                &cloudwatch.Dimension{
                    Name:  aws.String("SiteName"),
                    Value: aws.String("example.com"),
                },
            },
        },
        &cloudwatch.MetricDatum{
            MetricName: aws.String("UniqueVisits"),
            Unit:       aws.String("Count"),
            Value:      aws.Float64(8628.0),
            Dimensions: []*cloudwatch.Dimension{
                &cloudwatch.Dimension{
                    Name:  aws.String("SiteName"),
                    Value: aws.String("example.com"),
                },
            },
        },
        &cloudwatch.MetricDatum{
            MetricName: aws.String("PageViews"),
            Unit:       aws.String("Count"),
            Value:      aws.Float64(18057.0),
            Dimensions: []*cloudwatch.Dimension{
                &cloudwatch.Dimension{
                    Name:  aws.String("PageURL"),
                    Value: aws.String("my-page.html"),
                },
            },
        },
    },
})
```

If there are any errors, print them out, otherwise list some information about the custom metrics.

```
if err != nil {
    fmt.Println("Error adding metrics:", err.Error())
    return
}

// Get information about metrics
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
    Namespace: aws.String("Site/Traffic"),
})
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()
    }
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/custom_metrics.go) on GitHub.

# Sending Events to Amazon CloudWatch Events


These Go examples show you how to use the AWS SDK for Go to:
+ Create and update a rule used to trigger an event
+ Define one or more targets to respond to an event
+ Send events that are matched to targets for handling

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/cloudwatch) repository on GitHub.

## Scenario


CloudWatch Events delivers a near real-time stream of system events that describe changes in AWS resources to any of various targets. Using simple rules, you can match events and route them to one or more target functions or streams.

In these examples, Go code is used to send events to CloudWatch Events. The code uses the AWS SDK for Go to manage instances by using these methods of the [CloudWatchEvents](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents) type:
+  [PutRule](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents.PutRule) 
+  [PutTargets](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents.PutTargets) 
+  [PutEvents](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents.PutEvents) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch Events. To learn more, see [Adding Events with PutEvents](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/AddEventsPutEvents.html) in the Amazon CloudWatch Events User Guide.

## Tasks Before You Start


To set up and run this example, you must first complete these tasks:

1. Create a Lambda function using the hello-world blueprint to serve as the target for events. To learn how, see [Step 1: Create an AWS Lambda function](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/LogEC2InstanceState.html) in the CloudWatch Events User Guide.

1. Create an IAM role whose policy grants permission to CloudWatch Events and that includes `events.amazonaws.com` as a trusted entity. For more information about creating an IAM role, see [Creating a Role to Delegate Permissions to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the IAM User Guide.

   Use the following role policy when creating the IAM role.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Sid": "CloudWatchEventsFullAccess",
         "Effect": "Allow",
         "Action": "events:*",
         "Resource": "*"
      },
      {
         "Sid": "IAMPassRoleForCloudWatchEvents",
         "Effect": "Allow",
         "Action": "iam:PassRole",
         "Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets"
      }
   ]
}
```

------

Use the following trust relationship when creating the IAM role.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Principal": {
            "Service": "events.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
      }
   ]
}
```

------

## Create a Scheduled Rule


Choose **Copy** to save the code locally.

Create the file `events_schedule_rule.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatchevents"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch Events client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create the cloudwatch events client
svc := cloudwatchevents.New(sess)
```

Call `PutRule`, supplying a name, `DEMO_EVENT`, ARN of the IAM role you created, `IAM_ROLE_ARN`, and an expression defining the schedule. Finally, display the ARN of the rule.

```
result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{
    Name:               aws.String("DEMO_EVENT"),
    RoleArn:            aws.String("IAM_ROLE_ARN"),
    ScheduleExpression: aws.String("rate(5 minutes)"),
})
fmt.Println("Rule ARN:", result.RuleArn)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/events_schedule_rule.go) on GitHub.

## Add a Lambda Function Target


Choose **Copy** to save the code locally.

Create the file `events_put_targets.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatchevents"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a new CloudWatch Events client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create the cloudwatch events client
svc := cloudwatchevents.New(sess)
```

Call `PutTargets`, supplying a name for the rule, `DEMO_EVENT`. For the target, specify the ARN of the Lambda function you created, `LAMBDA_FUNCTION_ARN`, and the ID of the rule, `myCloudWatchEventsTarget`. Print any errors, or a success message with any targets that failed.

```
result, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{
    Rule: aws.String("DEMO_EVENT"),
    Targets: []*cloudwatchevents.Target{
        &cloudwatchevents.Target{
            Arn: aws.String("LAMBDA_FUNCTION_ARN"),
            Id:  aws.String("myCloudWatchEventsTarget"),
        },
    },
})
fmt.Println("Success", result)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/events_put_targets.go) on GitHub.

## Send Events


Choose **Copy** to save the code locally.

Create the file `events_put_events.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatchevents"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch Events client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create the cloudwatch events client
svc := cloudwatchevents.New(sess)
```

Call `PutEvents`, supplying key-name value pairs in the `Details` field, and specifying the ARN of the Lambda function you created, `RESOURCE_ARN`. See [PutEventsRequestEntry](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#PutEventsRequestEntry) for a description of the fields. Finally, display the ingested events.

```
result, err := svc.PutEvents(&cloudwatchevents.PutEventsInput{
    Entries: []*cloudwatchevents.PutEventsRequestEntry{
        &cloudwatchevents.PutEventsRequestEntry{
            Detail:     aws.String("{ \"key1\": \"value1\", \"key2\": \"value2\" }"),
            DetailType: aws.String("appRequestSubmitted"),
            Resources: []*string{
                aws.String("RESOURCE_ARN"),
            },
            Source: aws.String("com.company.myapp"),
        },
    },
})
fmt.Println("Ingested events:", result.Entries)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/cloudwatch/events_put_events.go) on GitHub.

# Getting Log Events from CloudWatch


The following example lists up to 100 of the latest events for a log group’s log stream. Replace LOG-GROUP-NAME with the name of the CloudWatch log group and LOG-STREAM-NAME with the name of the log stream for the log group.

```
package main

import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)

// GetLogEvents retrieves CloudWatchLog events.
// Inputs:
//     sess is the current session, which provides configuration for the SDK's service clients
//     limit is the maximum number of log events to retrieve
//     logGroupName is the name of the log group
//     logStreamName is the name of the log stream
// Output:
//     If success, a GetLogEventsOutput object containing the events and nil
//     Otherwise, nil and an error from the call to GetLogEvents
func GetLogEvents(sess *session.Session, limit *int64, logGroupName *string, logStreamName *string) (*cloudwatchlogs.GetLogEventsOutput, error) {
    svc := cloudwatchlogs.New(sess)

    resp, err := svc.GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
        Limit:         limit,
        LogGroupName:  logGroupName,
        LogStreamName: logStreamName,
    })
    if err != nil {
        return nil, err
    }

    return resp, nil
}

func main() {
    limit := flag.Int64("l", 100, "The maximum number of events to retrieve")
    logGroupName := flag.String("g", "", "The name of the log group")
    logStreamName := flag.String("s", "", "The name of the log stream")
    flag.Parse()

    if *logGroupName == "" || *logStreamName == "" {
        fmt.Println("You must supply a log group name (-g LOG-GROUP) and log stream name (-s LOG-STREAM)")
        return
    }

    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    resp, err := GetLogEvents(sess, limit, logGroupName, logStreamName)
    if err != nil {
        fmt.Println("Got error getting log events:")
        fmt.Println(err)
        return
    }

    fmt.Println("Event messages for stream " + *logStreamName + " in log group  " + *logGroupName)

    gotToken := ""
    nextToken := ""

    for _, event := range resp.Events {
        gotToken = nextToken
        nextToken = *resp.NextForwardToken

        if gotToken == nextToken {
            break
        }

        fmt.Println("  ", *event.Message)
    }
}
```