Getting SerializationException while trying to PutLogEvents on cloudwatch using golang

故事扮演 提交于 2019-12-11 16:40:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/55196976/getting-serializationexception-while-trying-to-putlogevents-on-cloudwatch-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!