Manan
Manan

Reputation: 150

Getting SerializationException while trying to PutLogEvents on cloudwatch using golang

I am trying to achieve following using my program: Create log-group on aws cloudwatch Create log-stream under above log-group Put log-events under above log-stream

All this using go lang

package main

import (
    "time"
    "fmt"
    "github.com/jcxplorer/cwlogger"
    "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/aws"
)

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

    svc := cloudwatchlogs.New(sess)
    logGroupName := "my-log-group";
    logStreamName := "my-log-stream";
    logGroupInput := cloudwatchlogs.CreateLogGroupInput{LogGroupName: &logGroupName}
    svc.CreateLogGroup(&logGroupInput);
    logStreamInput := cloudwatchlogs.CreateLogStreamInput{LogGroupName: &logGroupName, LogStreamName: &logStreamName}
    svc.CreateLogStream(&logStreamInput)

    logevents := make([]*cloudwatchlogs.InputLogEvent, 1)

    logevents = append(logevents, &cloudwatchlogs.InputLogEvent{
        Message:   aws.String("Simple log message"),
        Timestamp: aws.Int64(111),
    })

    p := cloudwatchlogs.PutLogEventsInput{LogEvents: logevents, LogGroupName: &logGroupName, LogStreamName: &logStreamName}
    resp, err := svc.PutLogEvents(&p)
    if err != nil {
        panic(err)
    }
    fmt.Print("Next Token: {}", resp.NextSequenceToken)
}

Now when I run above code, it successfully creates log-group and log-stream and I can verify that in aws cloudwatch. But for some reason PutLogEvents fails with following error:

panic: SerializationException: 
    status code: 400, request id: 0685efcc-47e3-11e9-b528-81f33ec2f468

I am not sure what may be wrong here. Any suggestion or direction will be really helpful.

Thanks in advance.

Upvotes: 0

Views: 1667

Answers (1)

Manan
Manan

Reputation: 150

Reason for SerializationException was:logevents := make([]*cloudwatchlogs.InputLogEvent, 1) followed by append which created first empty entry in slice. I replaced code with logevents := make([]*cloudwatchlogs.InputLogEvent, 0) and it got resolved.

Additionally while debugging to find why logs were not getting populated I figured out that timestamp value used is not valid one. According to aws documentation timestamp for each event can't be older than 14 days and can't be more than 2hr in future. Here is link: https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html

Hope it will be helpful to someone facing similar issue in future.

Upvotes: 1

Related Questions