全部產品
Search
文件中心

Simple Log Service:使用GetLogs介面查詢日誌

更新時間:Jun 30, 2024

完成日誌採集後,您可以調用GetLogs介面查詢採集到的日誌。本文介紹GetLogs介面的典型使用樣本。

前提條件

  • 已建立RAM使用者並完成授權。具體操作,請參見建立RAM使用者並完成授權

  • 已配置環境變數ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET。具體操作,請參見在Linux、macOS和Windows系統配置環境變數

    重要
    • 阿里雲帳號的AccessKey擁有所有API的存取權限,建議您使用RAM使用者的AccessKey進行API訪問或日常營運。

    • 強烈建議不要把AccessKey ID和AccessKey Secret儲存到工程代碼裡,否則可能導致AccessKey泄露,威脅您帳號下所有資源的安全。

  • 已安裝Log ServicePython SDK 。具體操作,請參見安裝Python SDK

  • 已採集日誌。具體操作,請參見日誌採集

  • 已閱讀GetLogs介面的參數說明。更多資訊,請參考GetLogs

注意事項

  • 本樣本以華東1(杭州)的公網Endpoint為例,其公網Endpoint為https://cn-hangzhou.log.aliyuncs.com。如果您通過與Project同地區的其他阿里雲產品訪問Log Service,請使用內網Endpointhttps://cn-hangzhou-intranet.log.aliyuncs.com。關於Log Service支援的地區與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():
    # Log Service的服務入口。更多資訊,請參見服務入口。此處以杭州為例,其它地區請根據實際情況填寫。
    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'

    # 建立Log ServiceClient。
    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():
    # Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
    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'

    # 建立Log ServiceClient。
    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():
    # Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
    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'

    # 建立Log ServiceClient。
    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():
    # Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
    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'

    # 建立Log ServiceClient。
    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():
    # Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
    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'

    # 建立Log ServiceClient。
    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,您無需手動封裝請求和簽名操作,就可以快速對Log ServiceAPI進行調試。更多資訊,請參見OpenAPI開發人員門戶

  • 為滿足越來越多的自動化Log Service配置需求,Log Service提供命令列工具CLI(Command Line Interface)。更多資訊,請參見Log Service命令列工具CLI

  • 更多範例程式碼,請參見Aliyun Log Python On GitHub