一、首先需要安装SDK

安装Python SDK。

pip install -U aliyun-log-python-sdk

二、使用GetLogs接口查询日志

# encoding: utf-8
import time

from aliyun.log import *

def main():
    # 日志服务的服务入口。此处以杭州为例。
    endpoint = 'cn-hangzhou.log.aliyuncs.com'
    # 阿里云访问密钥AccessKey。
    access_key_id = 'access-id'
    access_key = 'access-key'

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

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

    # 使用关键字查询日志。
    query = input("请输入查询内容:")

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

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

    # query为查询语句,line参数控制返回日志条数,这边line取值为2,如果返回空,可以确认下时间范围是否正确。
    request = GetLogsRequest(project, logstore, from_time, to_time, '', query=query, line=2, 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()
            
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐