To pull logs from AWS CloudWatch Logs using Go, where the field play_id matches a specific input value, we can leverage the AWS SDK for Go (aws-sdk-go) and the FilterLogEvents API. Below is a well-structured, idiomatic Go function that performs this task efficiently.
✅ Key Features of the Function
- Uses AWS SDK Go v1 (most common and stable version as of writing).
- Filters logs using a CloudWatch Logs filter pattern like
{ $.play_id = "value" }.
- Automatically paginates through results to fetch all matching events.
- Allows optional start and end time range in Unix milliseconds.
- Returns a slice of
*cloudwatchlogs.FilteredLogEvent, which includes log messages and metadata.
📦 Prerequisites
Ensure you have the AWS SDK installed:
go get github.com/aws/aws-sdk-go
Also, ensure your AWS credentials are set up via environment variables, AWS CLI config, or IAM roles if running on AWS infrastructure.
🧩 Go Function Implementation
package cloudwatch
import (
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
// GetLogsByPlayID fetches CloudWatch Logs where play_id matches the given value.
// Optionally accepts start and end times in Unix milliseconds.
func GetLogsByPlayID(
logGroupName string,
playID string,
startTime, endTime *int64,
) ([]*cloudwatchlogs.FilteredLogEvent, error) {
// Create a new AWS session
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2"), // Change to your region
})
if err != nil {
return nil, fmt.Errorf("failed to create AWS session: %v", err)
}
// Create CloudWatch Logs service client
svc := cloudwatchlogs.New(sess)
var events []*cloudwatchlogs.FilteredLogEvent
// Construct filter pattern: { $.play_id = "playID" }
filterPattern := fmt.Sprintf("{ $.play_id = \"%s\" }", playID)
input := &cloudwatchlogs.FilterLogEventsInput{
LogGroupName: aws.String(logGroupName),
FilterPattern: aws.String(filterPattern),
}
// Set optional time range
if startTime != nil {
input.StartTime = startTime
}
if endTime != nil {
input.EndTime = endTime
}
// Paginate through results
err = svc.FilterLogEventsPages(input, func(page *cloudwatchlogs.FilterLogEventsOutput, lastPage bool) bool {
events = append(events, page.Events...)
return !lastPage
})
if err != nil {
return nil, fmt.Errorf("failed to filter log events: %v", err)
}
return events, nil
}
📌 Usage Example
Here's how you can use the function:
package main
import (
"fmt"
"time"
"your_module/cloudwatch" // Replace with your actual module path
)
func main() {
logGroupName := "/aws/lambda/your-lambda-function"
playID := "12345"
now := time.Now().UnixNano() / 1e6
startTime := now - 24*60*60*1000 // 24 hours ago
events, err := cloudwatch.GetLogsByPlayID(logGroupName, playID, &startTime, &now)
if err != nil {
panic(err)
}
fmt.Printf("Found %d matching log events:\n", len(events))
for _, event := range events {
fmt.Println(*event.Message)
}
}
📝 Notes
- Filter Pattern Syntax: Use
{ $.play_id = "value" } for JSON logs. If your logs are plain text, you can use substring matching like "play_id=value".
- Time Range: It's highly recommended to limit the time range for performance and cost reasons.
- AWS Credentials: Ensure your environment has valid AWS credentials (e.g., via
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, or IAM role).
✅ Output
The function returns a slice of *cloudwatchlogs.FilteredLogEvent objects. Each has fields like:
Message – the actual log message.
Timestamp – the event timestamp in milliseconds.
LogStreamName – the name of the stream that generated the event.
🛠️ Optional Enhancements
- Add retry logic for transient AWS errors.
- Add logging.
- Return only the message strings instead of full events if desired.
- Support multiple log groups.
This function provides a clean, reusable, and efficient way to query AWS CloudWatch Logs based on a specific field value like play_id.