全部产品
Search
文档中心

日志服务:使用GetLogs接口查询日志

更新时间:Oct 26, 2023

完成日志采集后,您可以调用GetLogs接口查询采集到的日志。本文介绍GetLogs接口的典型使用示例。

前提条件

  • 已创建RAM用户并完成授权。具体操作,请参见创建RAM用户并完成授权

  • 已配置环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET。具体操作,请参见配置环境变量

    重要
    • 阿里云账号的AccessKey拥有所有API的访问权限,建议您使用RAM用户的AccessKey进行API访问或日常运维。

    • 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。

  • 已安装日志服务Python SDK 。具体操作,请参见安装Python SDK

  • 已采集日志。具体操作,请参见日志采集

  • 已阅读GetLogs接口的参数说明。更多信息,请参考GetLogs

注意事项

  • 本示例以华东1(杭州)的公网Endpoint为例,其公网Endpoint为https://cn-hangzhou.log.aliyuncs.com。如果您通过与Project同地域的其他阿里云产品访问日志服务,请使用内网Endpointhttps://cn-hangzhou-intranet.log.aliyuncs.com。关于日志服务支持的地域与Endpoint的对应关系,请参见服务入口

  • 您可以在SDK代码的响应对象中调用is_completed()方法,用于判断本次查询是否精确。

    • 如果is_completed()方法的返回结果为true,表示本次查询已完成且查询精确,返回的查询结果是完整的。

    • 如果is_completed()方法的返回结果为false,表示本次查询已完成但查询不精确,返回的查询结果是不完整的。您需要重复请求,获取完整的查询结果。关于查询不精确的更多信息,请参见查询不精确可能原因

原始日志样例

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

示例

您可以参考以下Python代码示例,对日志进行查询和分析。

重要

您可以在GetLogs接口中,使用query参数设置查询和分析语句,相关说明如下:

  • 当设置query仅为查询语句时,line参数有效,用于控制返回日志条数。

  • 当设置query为查询和分析语句时,line参数无效,需使用Limit语法控制返回结果行数。更多信息,请参见LIMIT子句

关于查询和分析语句的更多信息,请参见基本语法

示例1:使用关键字查询日志

使用查询语句path-0/file-5查询日志。示例如下:

# encoding: utf-8
import time
import os
from aliyun.log import *

def main():
    # 日志服务的服务入口。更多信息,请参见服务入口。此处以杭州为例,其它地域请根据实际情况填写。
    endpoint = 'cn-hangzhou.log.aliyuncs.com'
    # 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
    access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    access_key = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')

    # Project和Logstore名称。
    project = 'your-project-name'
    logstore = 'your-logstore-name'

    # 创建日志服务Client。
    client = LogClient(endpoint, access_key_id, access_key)

    # 使用关键字path-0/file-5查询日志。
    query = 'path-0/file-5'

    # from_time和to_time表示查询日志的时间范围,UNIX时间戳格式。
    from_time = int(time.time()) - 3600
    to_time = time.time() + 3600

    print("ready to query logs from logstore %s" % logstore)

    # 本示例中,query参数用于设置查询语句;line参数用于控制返回日志条数,line取值为3。
    request = GetLogsRequest(project, logstore, from_time, to_time, '', query=query, line=3, offset=0, reverse=False)
    response = client.get_logs(request)
    # 打印查询结果。
    print('-------------Query is started.-------------')
    for log in response.get_logs():
        print(log.contents.items())
    print('-------------Query is finished.-------------')

if __name__ == '__main__':
    main()
            

返回结果示例如下:

ready to query logs from logstore your-logstore-name
-------------Query is started.-------------
dict_items([ ('remote_user', 'nhf3g'), ('time_local', '14/Feb/2022:06:49:28'),  ('request_uri', '/request/path-0/file-5')...])
dict_items([ ('remote_user', 'ysu'), ('time_local', '14/Feb/2022:06:49:38'),  ('request_uri', '/request/path-0/file-5')...])
dict_items([ ('remote_user', 'l_k'), ('time_local', '14/Feb/2022:06:49:38'),  ('request_uri', '/request/path-0/file-5')...])
-------------Query is finished.-------------

Process finished with exit code 0

示例2:指定特定字段查询日志

使用查询语句request_method:POST查询请求方法为POST的日志。为控制返回日志条数,设置line为3。示例如下:

# encoding: utf-8
import time
import os
from aliyun.log import *

def main():
    # 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
    endpoint = 'cn-hangzhou.log.aliyuncs.com'
    # 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
    access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    access_key = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')

    # Project和Logstore名称。
    project = 'your-project-name'
    logstore = 'your-logstore-name'

    # 创建日志服务Client。
    client = LogClient(endpoint, access_key_id, access_key)

    # 指定特定字段查询日志。
    # 查询请求方法为POST的日志。
    query = 'request_method:POST'

    # from_time和to_time表示查询日志的时间范围,UNIX时间戳格式。
    from_time = int(time.time()) - 3600
    to_time = time.time() + 3600

    print("ready to query logs from logstore %s" % logstore)

    # 本示例中,query参数用于设置查询语句;line参数用于控制返回日志条数,line取值为3。
    request = GetLogsRequest(project, logstore, from_time, to_time, '', query=query, line=3, offset=0, reverse=False)
    response = client.get_logs(request)
    # 打印查询结果。
    print('-------------Query is started.-------------')
    for log in response.get_logs():
        print(log.contents.items())
    print('-------------Query is finished.-------------')

if __name__ == '__main__':
    main()
            

返回结果示例如下:

ready to query logs from logstore your-logstore-name
-------------Query is started.-------------
dict_items([ ('remote_user', 'tv0m'), ('time_local', '14/Feb/2022:06:59:08'), ('request_method', 'POST')...])
dict_items([ ('remote_user', '6joc'), ('time_local', '14/Feb/2022:06:59:08'), ('request_method', 'POST')...])
dict_items([ ('remote_user', 'da8'), ('time_local', '14/Feb/2022:06:59:08'), ('request_method', 'POST')...])
-------------Query is finished.-------------

Process finished with exit code 0

示例3:使用SQL语句分析日志

使用查询和分析语句request_method:POST|select COUNT(*) as pv,统计POST请求的数量,示例如下:

# encoding: utf-8
import time
import os
from aliyun.log import *

def main():
    # 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
    endpoint = 'cn-hangzhou.log.aliyuncs.com'
    # 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
    access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    access_key = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')

    # Project和Logstore名称。
    project = 'your-project-name'
    logstore = 'your-logstore-name'

    # 创建日志服务Client。
    client = LogClient(endpoint, access_key_id, access_key)

    # 使用SQL语句分析日志。
    # 查询请求方法为POST的日志,并统计POST请求的PV数量。
    query = 'request_method:POST|select COUNT(*) as pv'

    # from_time和to_time表示查询日志的时间范围,UNIX时间戳格式。
    from_time = int(time.time()) - 3600
    to_time = time.time() + 3600

    print("ready to query logs from logstore %s" % logstore)

    # 该示例中,query参数用于设置查询和分析语句,line参数无效,返回条数以query参数中的设置为准,返回1条。
    request = GetLogsRequest(project, logstore, from_time, to_time, '', query=query, line=3, offset=0, reverse=False)
    response = client.get_logs(request)
    # 打印查询结果。
    print('-------------Query is started.-------------')
    for log in response.get_logs():
        print(log.contents.items())
    print('-------------Query is finished.-------------')

if __name__ == '__main__':
    main()
            

返回结果示例如下:

ready to query logs from logstore nginx-moni
-------------Query is started.-------------
dict_items([('pv', '2918')])
-------------Query is finished.-------------

Process finished with exit code 0

示例4:使用SQL分组分析日志

使用查询与分析语句request_method:POST|select host, COUNT(*) as pv group by host order by pv desc limit 5统计POST请求的数量,并且按照host进行分组,按照PV进行排序。示例如下:

# encoding: utf-8
import time
import os
from aliyun.log import *

def main():
    # 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
    endpoint = 'cn-hangzhou.log.aliyuncs.com'
    # 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
    access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    access_key = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')

    # Project和Logstore名称。
    project = 'your-project-name'
    logstore = 'your-logstore-name'

    # 创建日志服务Client。
    client = LogClient(endpoint, access_key_id, access_key)

    # 统计请求方法为POST的日志,并且按照host进行分组,按照PV排序。
    # SQL语法中的limit限制日志条数为5。
    query = 'request_method:POST|select host, COUNT(*) as pv group by host order by pv desc limit 5'

    # from_time和to_time表示查询日志的时间范围,UNIX时间戳格式。
    from_time = int(time.time()) - 3600
    to_time = time.time() + 3600

    print("ready to query logs from logstore %s" % logstore)

    # query参数用于设置查询和分析语句,line参数无效,返回条数以query参数中的设置为准,返回5条;reverse参数无效,按照SQL语句指定顺序返回。
    request = GetLogsRequest(project, logstore, from_time, to_time, '', query=query, line=3, offset=0, reverse=False)
    response = client.get_logs(request)
    # 打印查询结果。
    print('-------------Query is started.-------------')
    for log in response.get_logs():
        print(log.contents.items())
    print('-------------Query is finished.-------------')

if __name__ == '__main__':
    main()
            

返回结果示例如下:

ready to query logs from logstore nginx-moni
-------------Query is started.-------------
dict_items([('host', 'www.example.com'), ('pv', '7')])
dict_items([('host', 'www.example.org'), ('pv', '6')])
dict_items([('host', 'www.example.net'), ('pv', '6')])
dict_items([('host', 'www.example.edu'), ('pv', '5')])
dict_items([('host', 'www.aliyundoc.com'), ('pv', '4')])
-------------Query is finished.-------------

Process finished with exit code 0

示例5:将查询日志中部分字段写入本地文件

使用查询语句path-0/file-5查询日志,并将日志中某个字段的值写入本地文件log.txt。示例如下:

# encoding: utf-8
import time
import os
from aliyun.log import *

def main():
    # 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
    endpoint = 'cn-hangzhou.log.aliyuncs.com'
    # 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
    access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    access_key = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')

    # Project和Logstore名称。
    project = 'your-project-name'
    logstore = 'your-logstore-name'

    # 创建日志服务Client。
    client = LogClient(endpoint, access_key_id, access_key)

    # 使用关键字path-0/file-5查询日志。
    query = 'path-0/file-5'

    # from_time和to_time表示查询日志的时间范围,UNIX时间戳格式。
    from_time = int(time.time()) - 3600
    to_time = time.time() + 3600

    print("ready to query logs from logstore %s" % logstore)

    # 本示例中,query参数用于设置查询语句;line参数用于控制返回日志条数,line取值为3。
    request = GetLogsRequest(project, logstore, from_time, to_time, '', query=query, line=3, offset=0, reverse=False)
    response = client.get_logs(request)
    # 打印查询结果。
    print('-------------Query is started.-------------')
    for log in response.get_logs():
        print(log.contents.items())
    print('-------------Query is finished.-------------')
    
    # 取出log中key的值,并保存至本地文件。
    print('-------------Start writing logs to local files.-------------')
    for loglocal in response.get_logs():
        filename = 'log.txt'
        with open(filename, mode='a') as fileobject:
            fileobject.write(loglocal.contents.get('remote_user')+'\n')
    print('-------------Finishing writing logs to local files.-------------')

if __name__ == '__main__':
    main()            

返回结果示例如下:

ready to query logs from logstore your-logstore-name
-------------Query is started.-------------
dict_items([ ('remote_user', 'nhf3g'), ('time_local', '14/Feb/2022:06:49:28'),  ('request_uri', '/request/path-0/file-5')...])
dict_items([ ('remote_user', 'ysu'), ('time_local', '14/Feb/2022:06:49:38'),  ('request_uri', '/request/path-0/file-5')...])
dict_items([ ('remote_user', 'l_k'), ('time_local', '14/Feb/2022:06:49:38'),  ('request_uri', '/request/path-0/file-5')...])
-------------Query is finished.-------------
-------------Start writing logs to local files.-------------
-------------Finishing writing logs to local files.-------------

Process finished with exit code 0

同时,您运行文件目录下生成log.txt文件,其内容如下:

nhf3g
ysu
l_k

相关文档

  • 在调用API接口过程中,若服务端返回结果中包含错误信息,则表示调用API接口失败。您可以参考API错误码对照表查找对应的解决方法。更多信息,请参见API错误处理对照表
  • 阿里云OpenAPI开发者门户提供调试、SDK、示例和配套文档。通过OpenAPI,您无需手动封装请求和签名操作,就可以快速对日志服务API进行调试。更多信息,请参见OpenAPI开发者门户
  • 为满足越来越多的自动化日志服务配置需求,日志服务提供命令行工具CLI(Command Line Interface)。更多信息,请参见日志服务命令行工具CLI
  • 更多示例代码,请参见Aliyun Log Python On GitHub