Invoque la API GetLogs para consultar los registros recopilados mediante el SDK de Java de SLS.
Requisitos previos
Simple Log Service está activado. Para obtener más información, consulte Activate Simple Log Service.
El SDK de Simple Log Service para Java está inicializado. Para obtener más información, consulte Initialize Simple Log Service SDK for Java.
Notas de uso
-
En este ejemplo se utiliza el endpoint público de Simple Log Service correspondiente a la región China (Hangzhou). Endpoint:
https://cn-hangzhou.log.aliyuncs.com.Si desea acceder a Simple Log Service desde otros servicios de Alibaba Cloud que residen en la misma región que su proyecto, puede utilizar el endpoint interno de Simple Log Service:
https://cn-hangzhou-intranet.log.aliyuncs.com.Para obtener más información sobre las regiones y endpoints compatibles con Simple Log Service, consulte Endpoint.
-
Invoque
IsCompleted()en el objeto de respuesta del SDK para comprobar si el conjunto de resultados está completo.true: La consulta se ejecutó correctamente y el conjunto de resultados está completo.false: La consulta se ejecutó correctamente, pero el conjunto de resultados está incompleto. Repita la solicitud para obtener los resultados completos. Possible causes of inaccurate queries.
Parámetros
Parámetros de solicitud
Nombre | Tipo | Obligatorio | Descripción |
project | String | Sí | Nombre del proyecto. El proyecto en Simple Log Service se utiliza para aislar los recursos de diferentes usuarios y controlar el acceso a recursos específicos. Consulte Manage projects. |
logstore | String | Sí | Nombre del logstore. El logstore en Simple Log Service se utiliza para recopilar, almacenar y consultar registros. Consulte Manage Logstores. |
from | int | Sí | Inicio del intervalo de tiempo que se va a consultar. El valor es una marca de tiempo UNIX. Nota
|
to | int | Sí | Fin del intervalo de tiempo que se va a consultar. El valor es una marca de tiempo UNIX. Nota
|
topic | String | No | Tema de los registros. El valor predeterminado es una cadena vacía. Para obtener más información, consulte Log topics. |
query | String | No | Instrucción de búsqueda o análisis. Query and Analysis Overview. Para usar SQL Exclusive, agregue Nota Si query contiene una instrucción analítica (SQL), los parámetros line y offset no tienen efecto. Establézcalos en 0 y utilice la cláusula LIMIT para la paginación. Paginate query and analysis results. |
line | int | No | Válido solo para instrucciones de búsqueda. Número máximo de registros que se devolverán. Rango: de 0 a 100. Valor predeterminado: 100. |
offset | int | No | Válido solo para instrucciones de búsqueda. Fila inicial para la consulta. Valor predeterminado: 0. |
reverse | boolean | No | Indica si se deben devolver los registros en orden descendente según la marca de tiempo. Precisión: nivel de minuto.
Importante
|
powerSql | boolean | No | Indica si se debe usar Dedicated SQL. High-performance and accurate query and analysis (Dedicated SQL).
También puede habilitar Dedicated SQL agregando la configuración al parámetro query. |
scan | boolean | No | Indica si se debe usar el modo de escaneo para la consulta. |
forward | boolean | No | Solo para consultas de escaneo. true: recupera la página siguiente. false: recupera la página anterior. |
Parámetros de respuesta
Registro sin procesar
body_bytes_sent:1750
host:www.example.com
http_referer:www.example.com
http_user_agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; it-it) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27
http_x_forwarded_for:203.0.XX.XX
remote_addr:203.0.XX.XX
remote_user:p288
request_length:13741
request_method:GET
request_time:71
request_uri:/request/path-1/file-1
http_code:200
time_local:11/Aug/2021:06:52:27
upstream_response_time:0.66
Ejemplos de consulta y análisis
Los siguientes ejemplos en Java muestran patrones de consulta comunes.
Al invocar GetLogs con el SDK de Java de SLS:
Si
querycontiene solo una instrucción de búsqueda (por ejemplo,request_method:POST), el parámetrolinecontrola el número de registros devueltos (máximo 100). Para devolver más de 100 registros, use la cláusula LIMIT en SQL. LIMIT clause.Si
querycontiene una instrucción de consulta y análisis (por ejemplo,request_method:POST | SELECT host, COUNT(*) AS pv GROUP BY host LIMIT 5), el parámetrolinese ignora. Use la cláusula LIMIT en SQL para controlar el número de filas. LIMIT clause.
Ejemplo 1: Consulta de registros mediante una palabra clave
Consulte registros por la palabra clave path-0/file-5. El parámetro line limita los resultados a 3 registros.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;
public class GetLogsTest {
public static void main(String[] args) throws LogException {
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Enter the project name.
String project = "your-project-name";
// Set the endpoint for Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
String host = "cn-hangzhou.log.aliyuncs.com";
// Enter the Logstore name.
String logStore = "your-logstore-name";
// Create a Simple Log Service client.
Client client = new Client(host, accessId, accessKey);
// Execute a query in the specified Logstore.
try {
// Use the keyword "path-0/file-5" to query logs.
String query = "path-0/file-5";
int from = 1754449503;
int to = 1754449510;
// In this example, the query parameter is used to set the query statement. The line parameter is used to control the number of returned logs. The value is 3, and the maximum value is 100.
GetLogsRequest request = new GetLogsRequest(project, logStore, from, to, "", query);
GetLogsResponse logsResponse = client.GetLogs(request);
System.out.println("-------------Query is started.-------------");
System.out.println("Returned query result count :" + logsResponse.GetCount());
System.out.println("from time is :" + from);
System.out.println("to time is :" + to);
for (QueriedLog log : logsResponse.getLogs()) {
LogItem item = log.GetLogItem();
System.out.println("log time : " + item.mLogTime);
System.out.println("Jsonstring : " + item.ToJsonString());
}
System.out.println("-------------Query is finished.-------------");
} catch (LogException e) {
System.out.println("LogException e :" + e.toString());
System.out.println("error code :" + e.GetErrorCode());
System.out.println("error message :" + e.GetErrorMessage());
throw e;
}
}
}
Respuesta:
-------------Query is started.-------------
Returned query result count :3
from time is :1644573549
to time is :1644573849
log time : 1644573808
Jsonstring : {"remote_addr":"203.0.XX.XX","__topic__":"nginx_access_log","request_uri":"/request/path-0/file-5"...}
log time : 1644573808
Jsonstring : {"remote_addr":"203.0.XX.XX","__topic__":"nginx_access_log","request_uri":"/request/path-0/file-5"...}
log time : 1644573788
Jsonstring : {"remote_addr":"203.0.XX.XX","__topic__":"nginx_access_log","request_uri":"/request/path-0/file-5"...}
-------------Query is finished.-------------
Process finished with exit code 0
Ejemplo 2: Consulta de registros mediante la especificación de un campo
Consulte registros donde el método de solicitud sea POST. El parámetro line limita los resultados a 3 registros.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;
public class GetLogsTest {
public static void main(String[] args) throws LogException {
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Enter the project name.
String project = "your-project-name";
// Set the endpoint for Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
String host = "cn-hangzhou.log.aliyuncs.com";
// Enter the Logstore name.
String logStore = "your-logstore-name";
// Create a Simple Log Service client.
Client client = new Client(host, accessId, accessKey);
// Execute a query in the specified Logstore.
try {
// Query for logs where the request method is POST.
String query = "request_method:POST";
// Set the time range for the query.
int from = 1754449503;
int to = 1754449510;
// In this example, the query parameter is used to set the query statement. The line parameter is used to control the number of returned logs. The value is 3, and the maximum value is 100.
GetLogsRequest request = new GetLogsRequest(project, logStore, from, to, "", query);
GetLogsResponse logsResponse = client.GetLogs(request);
System.out.println("-------------Query is started.-------------");
System.out.println("Returned query result count :" + logsResponse.GetCount());
System.out.println("from time is :" + from);
System.out.println("to time is :" + to);
for (QueriedLog log : logsResponse.getLogs()) {
LogItem item = log.GetLogItem();
System.out.println("log time : " + item.mLogTime);
System.out.println("Jsonstring : " + item.ToJsonString());
}
System.out.println("-------------Query is finished.-------------");
} catch (LogException e) {
System.out.println("LogException e :" + e.toString());
System.out.println("error code :" + e.GetErrorCode());
System.out.println("error message :" + e.GetErrorMessage());
throw e;
}
}
}
Respuesta:
-------------Query is started.-------------
Returned query result count :3
from time is :1644574151
to time is :1644574451
log time : 1644574438
Jsonstring : {"remote_addr":"203.0.XX.XX","__topic__":"nginx_access_log","body_bytes_sent":"3604","request_method":"POST"...}
log time : 1644574438
Jsonstring : {"remote_addr":"203.0.XX.XX","__topic__":"nginx_access_log","body_bytes_sent":"3369","request_method":"POST"...}
log time : 1644574438
Jsonstring : {"remote_addr":"203.0.XX.XX","__topic__":"nginx_access_log","body_bytes_sent":"12714","request_method":"POST"...}
-------------Query is finished.-------------
Process finished with exit code 0
Ejemplo 3: Análisis de registros mediante una instrucción SQL
Consulte registros donde el método de solicitud sea POST y cuente las vistas de página (PV).
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;
public class GetLogsTest {
public static void main(String[] args) throws LogException {
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Enter the project name.
String project = "your-project-name";
// Set the endpoint for Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
String host = "cn-hangzhou.log.aliyuncs.com";
// Enter the Logstore name.
String logStore = "your-logstore-name";
// Create a Simple Log Service client.
Client client = new Client(host, accessId, accessKey);
// Execute a query in the specified Logstore.
try {
// Query for logs where the request method is POST and count the number of PVs for the POST requests.
String query = "request_method:POST|select COUNT(*) as pv";
// Set the time range for the query.
int from = 1754449503;
int to = 1754449510;
// In this example, the query parameter is set to a query and analysis statement. The line parameter is invalid.
GetLogsRequest request = new GetLogsRequest(project, logStore, from, to, "", query);
GetLogsResponse logsResponse = client.GetLogs(request);
System.out.println("-------------Query is started.-------------");
System.out.println("Returned query result count :" + logsResponse.GetCount());
System.out.println("from time is :" + from);
System.out.println("to time is :" + to);
for (QueriedLog log : logsResponse.getLogs()) {
LogItem item = log.GetLogItem();
System.out.println("log time : " + item.mLogTime);
System.out.println("Jsonstring : " + item.ToJsonString());
}
System.out.println("-------------Query is finished.-------------");
} catch (LogException e) {
System.out.println("LogException e :" + e.toString());
System.out.println("error code :" + e.GetErrorCode());
System.out.println("error message :" + e.GetErrorMessage());
throw e;
}
}
}
Respuesta:
-------------Query is started.-------------
Returned query result count :1
from time is :1644574354
to time is :1644574654
log time : 1644574354
Jsonstring : {"pv":"162","logtime":1644574354}
-------------Query is finished.-------------
Process finished with exit code 0
Ejemplo 4: Análisis de registros mediante la cláusula GROUP BY
Consulte registros donde el método de solicitud sea POST y agrupe los resultados por host.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;
public class GetLogsTest {
public static void main(String[] args) throws LogException {
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Enter the project name.
String project = "your-project-name";
// Set the endpoint for Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
String host = "cn-hangzhou.log.aliyuncs.com";
// Enter the Logstore name.
String logStore = "your-logstore-name";
// Create a Simple Log Service client.
Client client = new Client(host, accessId, accessKey);
// Execute a query in the specified Logstore.
try {
// Query for logs where the request method is POST and group the results by host.
// Use the LIMIT clause in the SQL syntax to limit the number of returned rows to 5.
String query = "request_method:POST|select host, COUNT(*) as pv group by host limit 5";
// Set the time range for the query.
int from = 1754449503;
int to = 1754449510;
// In this example, the query parameter is set to a query and analysis statement. The line parameter is invalid. The number of rows to return is determined by the LIMIT clause in the query.
GetLogsRequest request = new GetLogsRequest(project, logStore, from, to, "", query);
GetLogsResponse logsResponse = client.GetLogs(request);
System.out.println("-------------Query is started.-------------");
System.out.println("Returned query result count :" + logsResponse.GetCount());
System.out.println("from time is :" + from);
System.out.println("to time is :" + to);
for (QueriedLog log : logsResponse.getLogs()) {
LogItem item = log.GetLogItem();
System.out.println("log time : " + item.mLogTime);
System.out.println("Jsonstring : " + item.ToJsonString());
}
System.out.println("-------------Query is finished.-------------");
} catch (LogException e) {
System.out.println("LogException e :" + e.toString());
System.out.println("error code :" + e.GetErrorCode());
System.out.println("error message :" + e.GetErrorMessage());
throw e;
}
}
}
Respuesta:
-------------Query is started.-------------
Returned query result count :5
from time is :1644574445
to time is :1644574745
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example1.com","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example.org","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example.net","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example.edu","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.aliyundoc.com","logtime":1644574445}
-------------Query is finished.-------------
Process finished with exit code 0
Ejemplo 5: Análisis de registros mediante la cláusula GROUP BY (200 registros devueltos)
Consulte registros donde el método de solicitud sea POST, agrúpelos por host y devuelva hasta 200 filas mediante la cláusula LIMIT.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;
public class GetLogsTest {
public static void main(String[] args) throws LogException {
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Enter the project name.
String project = "your-project-name";
// Set the endpoint for Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
String host = "cn-hangzhou.log.aliyuncs.com";
// Enter the Logstore name.
String logStore = "your-logstore-name";
// Create a Simple Log Service client.
Client client = new Client(host, accessId, accessKey);
// Execute a query in the specified Logstore.
try {
// Query for logs where the request method is POST and group the results by host.
// Use the LIMIT clause in the SQL syntax to control the number of rows to return.
String query = "request_method:POST|select host, COUNT(*) as pv group by host limit 0,200";
// Set the time range for the query.
int from = 1754449503;
int to = 1754449510;
// In this example, the query parameter is set to a query and analysis statement. The line parameter is invalid. The number of rows to return is determined by the LIMIT clause in the query.
GetLogsRequest request = new GetLogsRequest(project, logStore, from, to, "", query);
GetLogsResponse logsResponse = client.GetLogs(request);
System.out.println("-------------Query is started.-------------");
System.out.println("Returned query result count :" + logsResponse.GetCount());
System.out.println("from time is :" + from);
System.out.println("to time is :" + to);
for (QueriedLog log : logsResponse.getLogs()) {
LogItem item = log.GetLogItem();
System.out.println("log time : " + item.mLogTime);
System.out.println("Jsonstring : " + item.ToJsonString());
}
System.out.println("-------------Query is finished.-------------");
} catch (LogException e) {
System.out.println("LogException e :" + e.toString());
System.out.println("error code :" + e.GetErrorCode());
System.out.println("error message :" + e.GetErrorMessage());
throw e;
}
}
}
Respuesta:
-------------Query is started.-------------
Returned query result count :200
from time is :1644574445
to time is :1644574745
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example1.com","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example.org","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example.net","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.example.edu","logtime":1644574445}
log time : 1644574445
Jsonstring : {"pv":"1","host":"www.aliyundoc.com","logtime":1644574445}
......
-------------Query is finished.-------------
Process finished with exit code 0
Ejemplo 6: Consulta del número total de registros en la última hora mediante una instrucción SQL
Use *|select count(*) as count para obtener el número total de registros de la última hora.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;
import java.util.Date;
public class GetLogsTest {
public static void main(String[] args) throws LogException {
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Enter the project name.
String project = "your-project-name";
// Set the endpoint for Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
String host = "cn-hangzhou.log.aliyuncs.com";
// Enter the Logstore name.
String logStore = "your-logstore-name";
// Create a Simple Log Service client.
Client client = new Client(host, accessId, accessKey);
// Execute a query in the specified Logstore.
try {
// Query the total number of logs.
String query = "*|select count(*) as count";
// Set the query time range to 1 hour (3,600 seconds).
int from = (int) (new Date().getTime() / 1000 - 3600);
int to = (int) (new Date().getTime() / 1000);
int offset = 0;
int line = 200;
// In this example, the SQL statement in the query parameter is used to query the total number of logs in the specified time range. The line and offset parameters are invalid for SQL queries.
GetLogsRequest request = new GetLogsRequest(project, logStore, from, to, "", query,line,offset,true);
GetLogsResponse logsResponse = client.GetLogs(request);
System.out.println("-------------Query is started.-------------");
System.out.println("Returned query result count :" + logsResponse.GetCount());
System.out.println("from time is :" + from);
System.out.println("to time is :" + to);
for (QueriedLog log : logsResponse.getLogs()) {
LogItem item = log.GetLogItem();
System.out.println("log time : " + item.mLogTime);
System.out.println("Jsonstring : " + item.ToJsonString());
}
System.out.println("-------------Query is finished.-------------");
} catch (LogException e) {
System.out.println("LogException e :" + e.toString());
System.out.println("error code :" + e.GetErrorCode());
System.out.println("error message :" + e.GetErrorMessage());
throw e;
}
}
}
El número total de registros en la última hora es 19,051. Respuesta:
from time is :1675041679
to time is :1675045279
Returned sql result count :1
Jsonstring : {"count":"19051","logtime":1675041679}
-------------Query is finished.-------------
Referencias
Además de su SDK nativo, SLS también admite los SDK comunes de Alibaba Cloud. Para obtener más información, consulte Simple Log Service_SDK Center_Alibaba Cloud OpenAPI Explorer.