Query log data in the logstore

Updated at:

Query raw log data in a specified logstore by calling the GetLogsV2 API. The response returns raw logs within a specified time range, compressed for transmission.

Prerequisites

Parameter description

def get_log_all_v2(self, project, logstore, from_time, to_time, topic=None, query=None, reverse=False, offset=0, power_sql=False, scan=False, forward=True):

Request parameters

Parameter

Type

Required

Description

project

string

Yes

The name of the project. The project in Simple Log Service is used to isolate the resources of different users and control access to specific resources. See Manage projects.

logstore

string

Yes

The name of the logstore. The logstore in Simple Log Service is used to collect, store, and query logs. See Manage Logstores.

from_time

int

Yes

The beginning of the time range to query. The value is a UNIX timestamp.

Note
  • The time when the logstore receives logs. The __tag__:__receive_time__ field is a reserved field of Simple Log Service.

  • The time range defined by the start time and the end time. The time range is a left-closed, right-open interval. The interval includes the start time of the time range, but not the end time. If both are the same, the interval is invalid and an error is returned.

  • To ensure that full data can be queried, specify a query time range that is accurate to the minute. If you also specify a time range in an analytic statement, the time range is used for query and analysis.

  • If you want to specify a time range that is accurate to the second, you can use date and time functions to convert the time format. Examples:

    • * | SELECT * FROM log WHERE from_unixtime(__time__) > from_unixtime(1664186624) AND from_unixtime(__time__) < now()

    • * | SELECT * FROM log WHERE __time__ > to_unixtime(date_parse('2022-10-19 15:46:05', '%Y-%m-%d %H:%i:%s')) AND __time__ < to_unixtime(now())

to_time

int

Yes

The end of the time range to query. The value is a UNIX timestamp.

Note
  • The time when the logstore receives logs. The __tag__:__receive_time__ field is a reserved field of Simple Log Service.

  • The time range defined by the start time and the end time. The time range is a left-closed, right-open interval. The interval includes the start time of the time range, but not the end time. If both are the same, the interval is invalid and an error is returned.

  • To ensure that full data can be queried, specify a query time range that is accurate to the minute. If you also specify a time range in an analytic statement, the time range is used for query and analysis.

  • If you want to specify a time range that is accurate to the second, you can use date and time functions to convert the time format. Examples:

    • * | SELECT * FROM log WHERE from_unixtime(__time__) > from_unixtime(1664186624) AND from_unixtime(__time__) < now()

    • * | SELECT * FROM log WHERE __time__ > to_unixtime(date_parse('2022-10-19 15:46:05', '%Y-%m-%d %H:%i:%s')) AND __time__ < to_unixtime(now())

topic

string

No

The topic of logs. The default value is an empty string. For more information, see Log topics.

query

string

No

Query statement or analytic statement. For more information, see Overview of log query and analysis. To use Dedicated SQL, add set session parallel_sql=true; in the analytic statement of query. For example, * | set session parallel_sql=true; select count(*) as pv. For common query and analysis issues, see Common log query and analysis errors.

Note

When query contains an analytic statement (SQL statement), the line and offset parameters are ignored. Set them to 0 and use the LIMIT syntax of SQL statements for paging. For more information, see Paginate query and analysis results.

line

int

No

Valid only when query is a query statement. Maximum number of log entries to return. Default value: 100. Minimum: 0. Maximum: 100.

offset

int

No

Valid only when query is a query statement. Line number from which the query starts. Default value: 0.

reverse

bool

No

Specifies whether to return logs in descending order by log timestamp. Timestamps are accurate to the minute.

  • True: Return logs in descending order by log timestamp.

  • False (default): Return logs in ascending order by log timestamp.

Important
  • When query is a query statement, reverse controls the sorting order of returned logs.

  • When query is a query and analysis statement, reverse is ignored. Use the order by clause in the SQL analytic statement instead.

power_sql

bool

No

Specifies whether to use Dedicated SQL. For more information, see High-performance fully accurate query and analysis (Dedicated SQL).

  • True: Use Dedicated SQL.

  • False (default): Use Standard SQL.

You can configure Dedicated SQL using either power_sql or query.

scan

bool

No

When set to True, the query runs in scan mode.

forward

bool

No

For scan queries only. When set to True, retrieves the next page; otherwise, retrieves the previous one.

Response parameters

For information about the response parameters, see GetLogsV2.

Sample code

from aliyun.log import LogClient, GetLogsRequest
import os
from datetime import datetime, timedelta

# In this example, the AccessKey ID and AccessKey secret are obtained from environment variables.
access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
access_key_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')

# Specify a Simple Log Service endpoint.
endpoint = "ap-southeast-1.log.aliyuncs.com"

client = LogClient(endpoint, access_key_id, access_key_secret)

project = "proj-test-1"
logstore = "logstore-1"
from_time = (datetime.now() - timedelta(minutes=1)).timestamp()
to_time = datetime.now().timestamp()


def main():
    # Query log data in the logstore. This API returns a generator.
    res = client.get_log_all_v2(project, logstore, from_time, to_time)
    for i in res:
        print(i.log_print())


if __name__ == '__main__':
    main()

Sample response

GetLogsResponse:
headers: {'Server': 'AliyunSLS', 'Content-Type': 'application/json', 'Content-Length': '849', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', 'Date': 'Tue, 15 Oct 2024 08:53:29 GMT', 'x-log-time': '1728982409', 'x-log-bodyrawsize': '1633', 'x-log-compresstype': 'deflate', 'x-log-requestid': '670E2D89****2DC5A1F'}
count: 1
progress: Complete
meta: {'count': 1, 'progress': 'Complete', 'processedRows': 1, 'elapsedMillisecond': 1, 'hasSQL': False, 'whereQuery': '', 'aggQuery': '', 'cpuSec': 0.0, 'cpuCores': 0, 'mode': 0, 'scanBytes': 0, 'phraseQueryInfo': None, 'limited': None, 'processedBytes': 0, 'telementryType': 'logging', 'powerSql': False, 'insertedSQL': None, 'keys': ['content', '__topic__', '__source__', '__tag__:__hostname__', '__tag__:__path__', '__tag__:__pack_id__', '__tag__:__receive_time__'], 'marker': None, 'isAccurate': True, 'columnTypes': None, 'highlights': None, 'terms': [{'key': '', 'term': '*'}]}

QueriedLog class:

QueriedLog:
time: 1728973611
source: 172.x.x.28
contents: {'content': '{"@timestamp":"2024-10-15T14:26:51+08:00","server_addr":"172.x.x.28","remote_addr":"192.x.x.1","scheme":"http","request_method":"POST","request_uri": "/admin-ajax.php","request_length": "1178","uri": "/admin-ajax.php", "request_time":0.030,"body_bytes_sent":112,"bytes_sent":669,"status":"200","upstream_time":"0.030","upstream_host":"unix:/dev/shm/php-cgi.sock","upstream_status":"200","host":"www.example.com","http_referer":"http://www.example.com/post.php?post=1&action=edit","http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.X.X Safari/537.36","request_body":"","content_type":"application/json; charset=UTF-8"}', '__topic__': '', '__tag__:__hostname__': '****', '__tag__:__path__': '/data/wwwlogs/json/www_json.log', '__tag__:__pack_id__': 'E56DA***44D05-4', '__tag__:__receive_time__': '1728973614'}


None
GetLogsResponse:
headers: {'Server': 'AliyunSLS', 'Content-Type': 'application/json', 'Content-Length': '173', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', 'Date': 'Tue, 15 Oct 2024 08:53:29 GMT', 'x-log-time': '1728982409', 'x-log-bodyrawsize': '260', 'x-log-compresstype': 'deflate', 'x-log-requestid': '670E2D89C74B0D57BB98F9A5'}
count: 0
progress: Complete
meta: {'count': 0, 'progress': 'Complete', 'processedRows': 0, 'elapsedMillisecond': 0, 'hasSQL': False, 'whereQuery': '', 'aggQuery': '', 'cpuSec': 0.0, 'cpuCores': 0, 'mode': 0, 'scanBytes': 0, 'phraseQueryInfo': None, 'limited': None, 'processedBytes': 0, 'telementryType': 'logging', 'powerSql': False, 'insertedSQL': None, 'keys': None, 'marker': None, 'isAccurate': True, 'columnTypes': None, 'highlights': None, 'terms': [{'key': '', 'term': '*'}]}

QueriedLog class:

None

Process finished with exit code 0

References