Este tópico descreve como usar o SDK do Simple Log Service (SLS) para Node.js para executar operações comuns, como criar projetos, logstores, gravar logs e consultar dados.
Pré-requisitos
O Simple Log Service está ativado. Ative o Simple Log Service.
O SDK do Simple Log Service para Node.js está instalado. Para mais informações, consulte Instale o SDK do Node.js.
Importante
Este exemplo usa o endpoint público da região China (Hangzhou): https://cn-hangzhou.log.aliyuncs.com. Se você acessar o SLS de outro serviço da Alibaba Cloud na mesma região do projeto, use o endpoint interno: https://cn-hangzhou-intranet.log.aliyuncs.com. Para obter mais informações sobre as regiões e os endpoints compatíveis com o SLS, consulte Endpoint.
Parâmetros
createProject
createLogStore
createIndex
getLogs
Exemplos
Escrever código Node.js para coletar logs
Neste exemplo, cria-se um arquivo chamado SLSQuickStart.js. O arquivo chama operações de API para criar um projeto, criar um logstore, criar um índice, gravar dados de log e consultar dados de log. O código abaixo fornece um exemplo:
const Client = require('@alicloud/log')
const sls = new Client({
// In this example, the AccessKey ID and AccessKey secret are obtained from environment variables.
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
// The endpoint of SLS. This example uses the endpoint of the China (Hangzhou) region. Replace it with the actual endpoint.
endpoint: 'cn-hangzhou.log.aliyuncs.com'
})
// Required. The name of the project.
const projectName = "aliyun-test-node-project"
// Required. The name of the logstore.
const logstoreName = "request_log"
async function test() {
// Create a project.
await sls.createProject(projectName, {
description: 'test'
})
// Create a logstore.
await sls.createLogStore(projectName, logstoreName, {
// Required. The data retention period in days. A value of 3650 indicates that the data is permanently stored.
ttl: 3600,
// Required. The number of shards.
shardCount: 2
})
// Create an index.
const index = {
"keys": {
"request_method": {
// Specifies whether the query is case-sensitive. false indicates that the query is case-insensitive.
"caseSensitive": false,
// Specifies whether to enable statistical analysis for the field.
"doc_value": true,
"token": ["\n", "\t", ";", ",", "=", ":"],
"type": "text"
}, "status": {
// Specifies whether the query is case-sensitive. false indicates that the query is case-insensitive.
"caseSensitive": false,
// Specifies whether to enable statistical analysis for the field.
"doc_value": true,
"token": ["\n", "\t", ";", ",", "=", ":"],
"type": "long"
}
},
}
await sls.createIndex(projectName, logstoreName, index)
// Write logs.
const logGroup = {
logs: [
{ content: { request_method: 'GET', status: '200' }, timestamp: Math.floor(new Date().getTime() / 1000) },
{ content: { request_method: 'GET', status: '500' }, timestamp: Math.floor(new Date().getTime() / 1000) },
{ content: { request_method: 'GET', status: '200' }, timestamp: Math.floor(new Date().getTime() / 1000) },
{ content: { request_method: 'POST', status: '500'}, timestamp: Math.floor(new Date().getTime() / 1000) }
],
tags: [{ tag1: 'testTag' }],
topic: 'testTopic',
source: 'testSource'
};
await sls.postLogStoreLogs(projectName, logstoreName, logGroup);
// Query example 1: Query the log data of the last day.
const from = new Date();
from.setDate(from.getDate() - 1);
const to = new Date();
const res = await sls.getLogs(projectName, logstoreName, from, to);
// Query example 2: Use a query statement to count the number of logs in the last 10 minutes.
// const from = new Date();
// from.setSeconds(from.getSeconds() - 600)
// const to = new Date();
// query = '* | select count(*) as count';
// topic = 'testTopic';
// const res = await sls.getLogs(projectName,logstoreName,from,to,{
// query: query,
// topic: topic,
// line: 100,
// offset: 0,
// reverse: false,
// powersql: false
// });
console.log(res)
}
// Run the function.
test()
O código a seguir mostra um exemplo de resposta:
[
{
request_method: 'GET',
status: '200',
__topic__: 'testTopic',
__source__: 'testSource',
'__tag__:tag1': 'testTag',
__time__: '1744882259'
},
{
request_method: 'GET',
status: '500',
__topic__: 'testTopic',
__source__: 'testSource',
'__tag__:tag1': 'testTag',
__time__: '1744882259'
},
{
request_method: 'GET',
status: '200',
__topic__: 'testTopic',
__source__: 'testSource',
'__tag__:tag1': 'testTag',
__time__: '1744882259'
},
{
request_method: 'POST',
status: '500',
__topic__: 'testTopic',
__source__: 'testSource',
'__tag__:tag1': 'testTag',
__time__: '1744882259'
}
]
A tabela a seguir fornece mais exemplos de código para referência.
|
GitHub source code |
Description |
|
Cria projetos, logstores e índices. Grava e consulta logs e logstores. Obtém distribuições de logs. |
Coletar logs Node.js usando Logtail
Para ver um exemplo de como usar o Logtail para coletar logs log4js de uma aplicação Node.js, consulte Collect Node.js logs.