全部產品
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 ServiceJava SDK。具體操作,請參見安裝Java SDK

  • 已瞭解GetLogs介面的各參數說明。更多資訊,請參見GetLogs

  • 該文檔中範例程式碼基於aliyun-log-0.6.69版本。若您在調試中出現沒有對應方法的報錯(例如無getLogs方法)或版本衝突問題,請升級到最新版本或更換版本後重試。

注意事項

  • 本樣本以華東1(杭州)的公網Endpoint為例,其公網Endpoint為https://cn-hangzhou.log.aliyuncs.com。如果您通過與Project同地區的其他阿里雲產品訪問Log Service,請使用內網Endpointhttps://cn-hangzhou-intranet.log.aliyuncs.com。關於Log Service支援的地區與Endpoint的對應關係,請參見服務入口

  • 您可以在SDK代碼的響應對象中調用IsCompleted()方法,用於判斷本次查詢是否精確。

    • 如果IsCompleted()方法的返回結果為true,表示本次查詢已完成且查詢精確,返回的查詢結果是完整的。

    • 如果IsCompleted()方法的返回結果為 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

查詢和分析日誌樣本

您可以參考以下程式碼範例,對日誌進行查詢和分析。

重要

在JAVA SDK中調用GetLogs介面的相關限制說明如下:

  • 當設定query僅為查詢語句(例如request_method:POST)時,可通過line參數控制返回日誌的條數,最大值為100。如果您需要返回更多的日誌,需使用SQL Limit文法。更多資訊,請參見LIMIT子句

  • 當設定query為查詢和分析語句(request_method:POST | SELECT host, COUNT(*) AS pv GROUP BY host LIMIT 5)時,line參數無效,需使用SQL Limit文法控制返回結果行數。更多資訊,請參見LIMIT子句

關於查詢和分析語句的更多資訊,請參見基本文法

樣本1:使用關鍵字查詢日誌

本樣本中將展示如何建立一個GetLogsTest.java檔案,並使用關鍵字path-0/file-5查詢日誌。為控制返回日誌條數,設定line參數為3。樣本如下:

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.response.GetLogsResponse;

import java.util.Date;

public class GetLogsTest {

    public static void main(String[] args) throws LogException {
         // 本樣本從環境變數中擷取AccessKey ID和AccessKey Secret。
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // 輸入Project名稱。
        String project = "your-project-name";
        // 設定Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
        String host = "cn-hangzhou.log.aliyuncs.com";
        // 輸入Logstore名稱。
        String logStore = "your-logstore-name";

        // 建立Log ServiceClient。
        Client client = new Client(host, accessId, accessKey);

        // 在指定的Logstore內執行查詢。
        try {
            // 使用關鍵字path-0/file-5查詢日誌。
            String query = "path-0/file-5";

            int from = (int) (new Date().getTime() / 1000 - 300);
            int to = (int) (new Date().getTime() / 1000);

            // 本樣本中,query參數用於設定查詢語句;line參數用於控制返回日誌條數,取值為3,最大值為100。
            GetLogsResponse logsResponse = client.GetLogs(project, logStore, from, to, "", query, 3, 0,true);
            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;
        }
    }
}

返回結果樣本如下:

-------------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

樣本2:指定特定欄位查詢日誌

本樣本中將展示如何建立一個GetLogsTest.java檔案,並查詢要求方法為POST的日誌。為控制返回日誌條數,設定line參數為3。樣本如下:

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.response.GetLogsResponse;

import java.util.Date;

public class GetLogsTest {

    public static void main(String[] args) throws LogException {
        // 本樣本從環境變數中擷取AccessKey ID和AccessKey Secret。
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // 輸入Project名稱。
        String project = "your-project-name";
        // 設定Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
        String host = "cn-hangzhou.log.aliyuncs.com";
        // 輸入Logstore名稱。
        String logStore = "your-logstore-name";

        // 建立Log ServiceClient。
        Client client = new Client(host, accessId, accessKey);

        // 在指定的Logstore內執行SQL分析。
        try {
            // 統計要求方法為POST的日誌。
            String query = "request_method:POST";

            int from = (int) (new Date().getTime() / 1000 - 300);
            int to = (int) (new Date().getTime() / 1000);

            // 本樣本中,query參數用於設定查詢語句;line參數用於控制返回日誌條數,取值為3,最大值為100。
            GetLogsResponse logsResponse = client.GetLogs(project, logStore, from, to, "", query, 3, 0,true);
            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;
        }
    }
}

返回結果樣本如下:

-------------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

樣本3:使用SQL語句分析日誌

本樣本中將展示如何建立一個GetLogsTest.java檔案,查詢要求方法為POST的日誌,並統計POST請求的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.response.GetLogsResponse;

import java.util.Date;

public class GetLogsTest {

    public static void main(String[] args) throws LogException {
        // 本樣本從環境變數中擷取AccessKey ID和AccessKey Secret。
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // 輸入Project名稱。
        String project = "your-project-name";
        // 設定Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
        String host = "cn-hangzhou.log.aliyuncs.com";
        // 輸入Logstore名稱。
        String logStore = "your-logstore-name";

        // 建立Log ServiceClient。
        Client client = new Client(host, accessId, accessKey);

        // 在指定的Logstore內執行SQL分析。
        try {
            // 查詢要求方法為POST的日誌,並統計POST請求的PV數量。
            String query = "request_method:POST|select COUNT(*) as pv";

            int from = (int) (new Date().getTime() / 1000 - 300);
            int to = (int) (new Date().getTime() / 1000);

            // 本樣本中,query參數用於設定查詢和分析語句,line參數無效,返回條數以query參數中的設定為準,返回1條。
            GetLogsResponse logsResponse = client.GetLogs(project, logStore, from, to, "", query, 3, 0,true);
            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;
        }
    }
}

返回結果樣本如下:

-------------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

樣本4:使用SQL分組分析日誌

本樣本中將展示如何建立一個GetLogsTest.java檔案,查詢要求方法為POST的日誌並且按照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.response.GetLogsResponse;

import java.util.Date;

public class GetLogsTest {

    public static void main(String[] args) throws LogException {
        // 本樣本從環境變數中擷取AccessKey ID和AccessKey Secret。
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // 輸入Project名稱。
        String project = "your-project-name";
        // 設定Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
        String host = "cn-hangzhou.log.aliyuncs.com";
        // 輸入Logstore名稱。
        String logStore = "your-logstore-name";

        // 建立Log ServiceClient。
        Client client = new Client(host, accessId, accessKey);

        // 在指定的Logstore內執行SQL分析。
        try {
            // 統計要求方法為POST的日誌並且按照host進行分組。
            // 使用SQL文法中的limit語句限制條數為5。
            String query = "request_method:POST|select host, COUNT(*) as pv group by host limit 5";

            int from = (int) (new Date().getTime() / 1000 - 300);
            int to = (int) (new Date().getTime() / 1000);

            // 本樣本中,query參數用於設定查詢和分析語句,line參數無效,返回條數以query參數中的設定為準,返回5條。
            GetLogsResponse logsResponse = client.GetLogs(project, logStore, from, to, "", query, 3, 0,true);
            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;
        }
    }
}

返回結果樣本如下:

-------------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

樣本5:使用SQL分組分析日誌(返回200條)

本樣本中將展示如何建立一個GetLogsTest.java檔案,查詢要求方法為POST的日誌並且按照host進行分組,返回200條日誌。樣本如下:

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.response.GetLogsResponse;

import java.util.Date;

public class GetLogsTest {

    public static void main(String[] args) throws LogException {
        // 本樣本從環境變數中擷取AccessKey ID和AccessKey Secret。
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // 輸入Project名稱。
        String project = "your-project-name";
        // 設定Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
        String host = "cn-hangzhou.log.aliyuncs.com";
        // 輸入Logstore名稱。
        String logStore = "your-logstore-name";

        // 建立Log ServiceClient。
        Client client = new Client(host, accessId, accessKey);

        // 在指定的Logstore內執行SQL分析。
        try {
            //統計要求方法為POST的日誌並且按照host進行分組。
            //使用SQL文法中的limit語句控制返回條數。
            String old_query = "request_method:POST|select host, COUNT(*) as pv group by host limit ";

            int from = (int) (new Date().getTime() / 1000 - 300);
            int to = (int) (new Date().getTime() / 1000);
            int log_offset = 0;
            int log_line = 200;
            
            String query = old_query + log_offset + "," + log_line;

            // 本樣本中,query參數用於設定查詢和分析語句,line參數無效,返回條數以query參數中的設定為準。
            GetLogsResponse logsResponse = client.GetLogs(project, logStore, from, to, "", query, 10, 0 ,true);
            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;
        }
    }
}

返回結果樣本如下:

-------------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

樣本6:使用SQL統計過去一小時內的日誌總條數

本樣本中將展示如何建立一個GetLogsTest.java檔案,並使用SQL語句*|select count(*) as count查詢過去一小時內的日誌總條數。樣本如下:

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.response.GetLogsResponse;

import java.util.Date;

public class GetLogsTest {

    public static void main(String[] args) throws LogException {
        // 本樣本從環境變數中擷取AccessKey ID和AccessKey Secret。
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // 輸入Project名稱。
        String project = "your-project-name";
        // 設定Log Service的存取點。此處以杭州為例,其它地區請根據實際情況填寫。
        String host = "cn-hangzhou.log.aliyuncs.com";
        // 輸入Logstore名稱。
        String logStore = "your-logstore-name";

        // 建立Log ServiceClient。
        Client client = new Client(host, accessId, accessKey);

        // 在指定的Logstore內執行SQL分析。
        try {
            // 查詢日誌總條數。
            String query = "*|select count(*) as count";
            // 查詢時間區間為1小時(3600秒)。
            int from = (int) (new Date().getTime() / 1000 - 3600);
            int to = (int) (new Date().getTime() / 1000);
            int log_offset = 0;
            int log_line = 200;

            // 本樣本中,query參數中的SQL語句用於查詢該時間區間中日誌總條數。
            GetLogsResponse logsResponse = client.GetLogs(project, logStore, from, to, "", query, log_line, log_offset,true);
            System.out.println("-------------Query is started.-------------");
            System.out.println("from time is :" + from);
            System.out.println("to time is :" + to);
            System.out.println("Returned query result count :" + logsResponse.GetCount());

            for (QueriedLog log : logsResponse.getLogs()) {
                LogItem item = log.GetLogItem();
                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;
        }
    }
}

從返回結果可以看出,過去一小時內的日誌總條數為19051條。返回結果樣本如下:

from time is :1675041679
to time is :1675045279
Returned sql result count :1
Jsonstring : {"count":"19051","logtime":1675041679}
-------------Query is finished.-------------

相關文檔

  • 在調用API介面過程中,若服務端返回結果中包含錯誤資訊,則表示調用API介面失敗。您可以參考API錯誤碼對照表尋找對應的解決方案。更多資訊,請參見API錯誤處理對照表

  • 阿里雲OpenAPI開發人員門戶提供調試、SDK、樣本和配套文檔。通過OpenAPI,您無需手動封裝請求和簽名操作,就可以快速對Log ServiceAPI進行調試。更多資訊,請參見OpenAPI開發人員門戶

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

  • 更多範例程式碼,請參見Aliyun Log Java SDK on GitHub

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