Use o Simple Log Service (SLS) SDK for Java para criar um projeto, um logstore e um índice e, em seguida, grave e consulte dados de log.
Pré-requisitos
Antes de começar, verifique se você tem:
Java Runtime Environment (JRE) 6,0 ou posterior instalado. Execute
java -versionpara verificar. Se o Java não estiver instalado, baixe-o no site oficial do Java.SLS SDK for Java instalado. Para obter instruções de instalação, consulte Instalar o SLS SDK for Java.
-
Um AccessKey ID e um AccessKey secret criados no console do Alibaba Cloud e armazenados como variáveis de ambiente:
export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>
Etapa 1: Inicializar o cliente
Todas as etapas deste tutorial compartilham uma única instância de Client. O endpoint define qual região processa suas solicitações.
import com.aliyun.openservices.log.Client;
public class SlsQuickStart {
// Obtain credentials from environment variables
static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// SLS endpoint for China (Hangzhou). Replace with your region endpoint.
static String host = "cn-hangzhou.log.aliyuncs.com";
static Client client = new Client(host, accessId, accessKey);
}
Substitua cn-hangzhou.log.aliyuncs.com pelo endpoint da sua região. O formato do endpoint é <region-id>.log.aliyuncs.com.
Etapa 2: Criar um projeto
O projeto é o contêiner de recursos de nível superior no SLS. Logstores, índices e painéis pertencem a um projeto.
static String projectName = "aliyun-test-gs-project";
static void createProject() throws LogException, InterruptedException {
String projectDescription = "project description";
System.out.println("ready to create project");
client.CreateProject(projectName, projectDescription);
System.out.println(String.format("create project %s success", projectName));
// Wait for the project to become fully available after creation
TimeUnit.SECONDS.sleep(60 * 2);
}
A espera de 2 minutos considera o tempo necessário para que o projeto fique totalmente disponível. Em produção, use lógica de polling ou novas tentativas em vez de uma pausa fixa.
Etapa 3: Criar um logstore
O logstore coleta, armazena e permite consultar dados de log dentro de um projeto. Configure o período de retenção e a quantidade de shards conforme sua carga de trabalho.
static String logstoreName = "aliyun-test-logstore";
static void createLogstore() throws LogException, InterruptedException {
System.out.println("ready to create logstore");
int ttlInDay = 3; // Data retention period in days. Set to 3650 for permanent storage.
int shardCount = 2; // Number of shards for read/write throughput
LogStore store = new LogStore(logstoreName, ttlInDay, shardCount);
client.CreateLogStore(projectName, store);
System.out.println(String.format("create logstore %s success", logstoreName));
// Wait for the logstore to become available
TimeUnit.SECONDS.sleep(60);
}
|
Parâmetro |
Descrição |
Exemplo |
|
|
Período de retenção de dados em dias. Defina como |
|
|
|
Quantidade de shards. Mais shards aumentam o throughput de leitura e gravação. |
|
Etapa 4: Criar um índice
Um índice habilita a pesquisa e a análise de logs em um logstore. Este exemplo cria um índice de texto completo e índices de campo para os campos dev e id.
static void createIndex() throws LogException, InterruptedException {
System.out.println(String.format("ready to create index for %s", logstoreName));
// Index configuration:
// - Full-text index with standard tokenizers (comma, space, quotes, brackets, etc.)
// - Field index on "dev" (text type) and "id" (long type)
// - Case-insensitive, Chinese tokenization disabled, max text length 2048
String logstoreIndex = "{\"line\": {\"token\": [\",\", \" \", \"'\", \"\\\"\", \";\", \"=\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", \"?\", \"@\", \"&\", \"<\", \">\", \"/\", \":\", \"\\n\", \"\\t\", \"\\r\"], \"caseSensitive\": false, \"chn\": false}, \"keys\": {\"dev\": {\"type\": \"text\", \"token\": [\",\", \" \", \"'\", \"\\\"\", \";\", \"=\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", \"?\", \"@\", \"&\", \"<\", \">\", \"/\", \":\", \"\\n\", \"\\t\", \"\\r\"], \"caseSensitive\": false, \"alias\": \"\", \"doc_value\": true, \"chn\": false}, \"id\": {\"type\": \"long\", \"alias\": \"\", \"doc_value\": true}}, \"log_reduce\": false, \"max_text_len\": 2048}";
Index index = new Index();
index.FromJsonString(logstoreIndex);
client.CreateIndex(projectName, logstoreName, index);
System.out.println(String.format("create index for %s success", logstoreName));
// Wait for the index to become available
TimeUnit.SECONDS.sleep(60);
}
O JSON do índice configura os seguintes parâmetros:
|
Configuração |
Valor |
Descrição |
|
Tokens de índice de texto completo |
|
Delimitadores para tokenização do texto de log |
|
|
|
Pesquisa sem distinção entre maiúsculas e minúsculas |
|
|
|
Tokenização chinesa desativada |
|
Campo |
|
Campo de texto com análise ativada ( |
|
Campo |
|
Campo numérico com análise ativada ( |
|
|
|
Comprimento máximo de texto para indexação |
Etapa 5: Gravar dados de log
Grave 100 eventos de log de exemplo no logstore. Cada evento contém um campo id e um campo dev.
static void pushLogs() throws LogException, InterruptedException {
System.out.println(String.format("ready to push logs for %s", logstoreName));
List<LogItem> logGroup = new ArrayList<LogItem>();
for (int i = 0; i < 100; ++i) {
LogItem logItem = new LogItem();
logItem.PushBack("id", String.valueOf(i));
logItem.PushBack("dev", "test_push");
logGroup.add(logItem);
}
client.PutLogs(projectName, logstoreName, "", logGroup, "");
System.out.println(String.format("push logs for %s success", logstoreName));
// Brief wait for logs to be indexed
TimeUnit.SECONDS.sleep(5);
}
O método PutLogs é adequado para cenários de baixo volume. Para cargas de trabalho com alto throughput ou alta concorrência, use o Alibaba Cloud Log Java Producer , que oferece envio em lote, novas tentativas e envio assíncrono.
Etapa 6: Consultar logs
Execute uma consulta SQL para recuperar eventos de log do logstore em uma janela de uma hora.
static String query = "*| select * from " + logstoreName;
static void queryLogs() throws LogException {
System.out.println(String.format("ready to query logs from %s", logstoreName));
// Query the last hour. fromTime and toTime are UNIX timestamps in seconds.
int fromTime = (int) (System.currentTimeMillis() / 1000 - 3600);
int toTime = fromTime + 3600;
GetLogsResponse getLogsResponse = client.GetLogs(projectName, logstoreName, fromTime, toTime, "", query);
for (QueriedLog log : getLogsResponse.getLogs()) {
for (LogContent mContent : log.mLogItem.mContents) {
System.out.println(mContent.mKey + " : " + mContent.mValue);
}
System.out.println("********************");
}
}
Código completo
O exemplo a seguir combina todas as etapas anteriores em um único programa executável. Crie um arquivo chamado SlsQuickStart.java e cole o código abaixo.
import com.aliyun.openservices.log.common.Index;
import com.aliyun.openservices.log.common.LogContent;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.LogStore;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.GetLogsResponse;
import com.aliyun.openservices.log.Client;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SlsQuickStart {
// Obtain credentials from environment variables
static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// SLS endpoint for China (Hangzhou). Replace with your region endpoint.
static String host = "cn-hangzhou.log.aliyuncs.com";
static Client client = new Client(host, accessId, accessKey);
static String projectName = "aliyun-test-gs-project";
static String logstoreName = "aliyun-test-logstore";
static String query = "*| select * from " + logstoreName;
static void createProject() throws LogException, InterruptedException {
String projectDescription = "project description";
System.out.println("ready to create project");
client.CreateProject(projectName, projectDescription);
System.out.println(String.format("create project %s success", projectName));
TimeUnit.SECONDS.sleep(60 * 2);
}
static void createLogstore() throws LogException, InterruptedException {
System.out.println("ready to create logstore");
int ttlInDay = 3;
int shardCount = 2;
LogStore store = new LogStore(logstoreName, ttlInDay, shardCount);
client.CreateLogStore(projectName, store);
System.out.println(String.format("create logstore %s success", logstoreName));
TimeUnit.SECONDS.sleep(60);
}
static void createIndex() throws LogException, InterruptedException {
System.out.println(String.format("ready to create index for %s", logstoreName));
String logstoreIndex = "{\"line\": {\"token\": [\",\", \" \", \"'\", \"\\\"\", \";\", \"=\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", \"?\", \"@\", \"&\", \"<\", \">\", \"/\", \":\", \"\\n\", \"\\t\", \"\\r\"], \"caseSensitive\": false, \"chn\": false}, \"keys\": {\"dev\": {\"type\": \"text\", \"token\": [\",\", \" \", \"'\", \"\\\"\", \";\", \"=\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", \"?\", \"@\", \"&\", \"<\", \">\", \"/\", \":\", \"\\n\", \"\\t\", \"\\r\"], \"caseSensitive\": false, \"alias\": \"\", \"doc_value\": true, \"chn\": false}, \"id\": {\"type\": \"long\", \"alias\": \"\", \"doc_value\": true}}, \"log_reduce\": false, \"max_text_len\": 2048}";
Index index = new Index();
index.FromJsonString(logstoreIndex);
client.CreateIndex(projectName, logstoreName, index);
System.out.println(String.format("create index for %s success", logstoreName));
TimeUnit.SECONDS.sleep(60);
}
static void pushLogs() throws LogException, InterruptedException {
System.out.println(String.format("ready to push logs for %s", logstoreName));
List<LogItem> logGroup = new ArrayList<LogItem>();
for (int i = 0; i < 100; ++i) {
LogItem logItem = new LogItem();
logItem.PushBack("id", String.valueOf(i));
logItem.PushBack("dev", "test_push");
logGroup.add(logItem);
}
client.PutLogs(projectName, logstoreName, "", logGroup, "");
System.out.println(String.format("push logs for %s success", logstoreName));
TimeUnit.SECONDS.sleep(5);
}
static void queryLogs() throws LogException {
System.out.println(String.format("ready to query logs from %s", logstoreName));
int fromTime = (int) (System.currentTimeMillis() / 1000 - 3600);
int toTime = fromTime + 3600;
GetLogsResponse getLogsResponse = client.GetLogs(projectName, logstoreName, fromTime, toTime, "", query);
for (QueriedLog log : getLogsResponse.getLogs()) {
for (LogContent mContent : log.mLogItem.mContents) {
System.out.println(mContent.mKey + " : " + mContent.mValue);
}
System.out.println("********************");
}
}
public static void main(String[] args) throws LogException, InterruptedException {
createProject();
createLogstore();
createIndex();
pushLogs();
queryLogs();
}
}
Saída esperada
Após executar o SlsQuickStart.java, o console exibe:
ready to create project
create project aliyun-test-gs-project success
ready to create logstore
create logstore aliyun-test-logstore success
ready to create index for aliyun-test-logstore
create index for aliyun-test-logstore success
ready to push logs for aliyun-test-logstore
push logs for aliyun-test-logstore success
ready to query logs from aliyun-test-logstore
dev : test_push
id : 0
********************
dev : test_push
id : 1
********************
dev : test_push
id : 2
********************
...
A saída real da consulta também pode incluir campos de metadados do sistema, como__line__,__topic__e__time___0.