Amazon Cloud Watch Log – PutLogEventsRequest – The given sequenceToken is invalid

Question:

I am building a small log tracker for my application using Amazon Cloud Watch service. The idea is not track log outputs on files and use search engine from aws console to find log information.

I am using:

  • Eclipse as IDE
  • Java 8
  • Dependencies : aws-java-sdk-core / aws-java-sdk-cloudwatch V 1.10.49

In the other hand I have the following AWS configuration:

  • Access and private keys
  • Region : California
  • Log group : demo1
  • Log stream : stream1

I was writing the following code to make a simple functional test:

When I run the code for the first time all is okey, the message is saved successfully.

enter image description here

However, when I execute the code for a second time I get the following exception:

XXXXXXXXXXX : Are token codes generated by amazon.

Reading the amazon documentation and I found the following info:

Request syntax:

SequenceToken

amazon documentation about cloud watch log REST API

And I decided to hard code the sequence token on my code as follows :

It works fine. And I made it just for test.

Finally, the only way that I found to get the sequence token was.

How can I validate and get the sequence code before make a request?. I can’t find that on the documentation.

Answer:

You normally get the nextToken when you do a call to putLogEvents (getNextSequenceToken). If there is more than one producer pushing to the stream, they are competing and only one of them can push at a time (ie: if you get a token and somebody else pushes it invalidates your token).

If this happens you need to describe the stream and get a new token: http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogStreams.html

So the pattern is:
1) If you don’t have a valid token or don’t have a token at all (you’re just starting) describe the stream to find out the token.
2) Push using the token you’ve got. If the push is successful update the token
3) If the push is not successful go to 1), get a new token and try again. You may need to try multiple times (ie loop) if multiple producers.

Leave a Reply