我正在使用 Amazon Cloud Watch 服务为我的应用程序构建一个小型日志跟踪器。这个想法不是跟踪文件的日志输出,而是使用 aws 控制台中的搜索引擎来查找日志信息。
我在用:
- Eclipse 作为 IDE
- 爪哇 8
- 依赖项:aws-java-sdk-core / aws-java-sdk-cloudwatch V 1.10.49
另一方面,我有以下 AWS 配置:
- 访问和私钥
- 地区:加利福尼亚
- 日志组:demo1
- 日志流:stream1
我正在编写以下代码来进行简单的功能测试:
package com.test.pe.cloudwatch;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.logs.AWSLogsClient;
import com.amazonaws.services.logs.model.InputLogEvent;
import com.amazonaws.services.logs.model.PutLogEventsRequest;
import com.amazonaws.services.logs.model.PutLogEventsResult;
import com.test.pe.base.CredentialBuilder;
public class RegisterLog {
private static String LOG_GROUP = "demo1";
private static String LOG_STREAM = "stream1";
public static void main(String[] args) throws ParseException {
// building my credential and calendar instances
AWSCredentials credential = CredentialBuilder.getCredential();
Calendar calendar = Calendar.getInstance();
// building a cloud watch log client
AWSLogsClient cloudWatchlog = new AWSLogsClient(credential);
cloudWatchlog.setRegion(Region.getRegion(Regions.US_WEST_1));
// building a put request log
PutLogEventsRequest request = new PutLogEventsRequest();
request.setLogGroupName(LOG_GROUP);
request.setLogStreamName(LOG_STREAM);
// building my log event
InputLogEvent log = new InputLogEvent();
log.setMessage("Some message for a test");
log.setTimestamp(calendar.getTimeInMillis());
// building the array list log event
ArrayList<InputLogEvent> logEvents = new ArrayList<InputLogEvent>();
logEvents.add(log);
// setting the error array list
request.setLogEvents(logEvents);
// make the request
cloudWatchlog.putLogEvents(request);
System.out.println("done!");
}
}
当我第一次运行代码时一切正常,消息已成功保存。
但是,当我第二次执行代码时,出现以下异常:
Exception in thread "main" com.amazonaws.services.logs.model.InvalidSequenceTokenException: The given sequenceToken is invalid. The next expected sequenceToken is: xxxxxxxxxxxxxxxxxxxxxxxxxxx (Service: AWSLogs; Status Code: 400; Error Code: InvalidSequenceTokenException; Request ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1389)
XXXXXXXXXXXX : 是亚马逊生成的令牌代码。
阅读亚马逊文档,我发现以下信息:
请求语法:
{
"LogEvents": [
{
"Message": "string",
"Timestamp": number
}
],
"LogGroupName": "string",
"LogStreamName": "string",
"SequenceToken": "string"
}
序列令牌
A string token that must be obtained from the response of the previous PutLogEvents request.
Type: String
Length constraints: Minimum length of 1.
Required: No
我决定在我的代码中硬编码序列标记,如下所示:
request.setSequenceToken("58523.......");
它工作正常。我做它只是为了测试。
最后,我发现获得序列令牌的唯一方法是。
PutLogEventsResult response = cloudWatchlog.putLogEvents(request);
String token = response.getNextSequenceToken();
如何在发出请求之前验证并获取序列码?我在文档上找不到。