StartQuery 搭配 AWS SDK 使用 - Amazon CloudWatch Logs

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

StartQuery 搭配 AWS SDK 使用

下列程式碼範例示範如何使用 StartQuery

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
適用於 .NET 的 SDK (v4)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Starts a CloudWatch Logs Insights query. /// </summary> /// <param name="logGroupName">The name of the log group to query.</param> /// <param name="queryString">The CloudWatch Logs Insights query string.</param> /// <param name="startTime">The start time for the query (seconds since epoch).</param> /// <param name="endTime">The end time for the query (seconds since epoch).</param> /// <param name="limit">The maximum number of results to return.</param> /// <returns>The query ID if successful, null otherwise.</returns> public async Task<string?> StartQueryAsync( string logGroupName, string queryString, long startTime, long endTime, int limit = 10000) { try { var request = new StartQueryRequest { LogGroupName = logGroupName, QueryString = queryString, StartTime = startTime, EndTime = endTime, Limit = limit }; var response = await _amazonCloudWatchLogs.StartQueryAsync(request); return response.QueryId; } catch (InvalidParameterException ex) { _logger.LogError($"Invalid parameter for query: {ex.Message}"); return null; } catch (ResourceNotFoundException ex) { _logger.LogError($"Log group not found: {ex.Message}"); return null; } catch (Exception ex) { _logger.LogError($"An error occurred while starting query: {ex.Message}"); return null; } }
  • 如需 API 詳細資訊,請參閱《適用於 .NET 的 AWS SDK API 參考》中的 StartQuery

JavaScript
適用於 JavaScript (v3) 的 SDK
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** * Wrapper for the StartQueryCommand. Uses a static query string * for consistency. * @param {[Date, Date]} dateRange * @param {number} maxLogs * @returns {Promise<{ queryId: string }>} */ async _startQuery([startDate, endDate], maxLogs = 10000) { try { return await this.client.send( new StartQueryCommand({ logGroupNames: this.logGroupNames, queryString: "fields @timestamp, @message | sort @timestamp asc", startTime: startDate.valueOf(), endTime: endDate.valueOf(), limit: maxLogs, }), ); } catch (err) { /** @type {string} */ const message = err.message; if (message.startsWith("Query's end date and time")) { // This error indicates that the query's start or end date occur // before the log group was created. throw new DateOutOfBoundsError(message); } throw err; } }
  • 如需 API 詳細資訊,請參閱《適用於 JavaScript 的 AWS SDK API 參考》中的 StartQuery

Python
適用於 Python 的 SDK (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

def perform_query(self, date_range): """ Performs the actual CloudWatch log query. :param date_range: A tuple representing the start and end datetime for the query. :type date_range: tuple :return: A list containing the query results. :rtype: list """ client = boto3.client("logs") try: try: start_time = round( self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[0]) ) end_time = round( self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[1]) ) response = client.start_query( logGroupName=self.log_group, startTime=start_time, endTime=end_time, queryString=self.query_string, limit=self.limit, ) query_id = response["queryId"] except client.exceptions.ResourceNotFoundException as e: raise DateOutOfBoundsError(f"Resource not found: {e}") while True: time.sleep(1) results = client.get_query_results(queryId=query_id) if results["status"] in [ "Complete", "Failed", "Cancelled", "Timeout", "Unknown", ]: return results.get("results", []) except DateOutOfBoundsError: return [] def _initiate_query(self, client, date_range, max_logs): """ Initiates the CloudWatch logs query. :param date_range: A tuple representing the start and end datetime for the query. :type date_range: tuple :param max_logs: The maximum number of logs to retrieve. :type max_logs: int :return: The query ID as a string. :rtype: str """ try: start_time = round( self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[0]) ) end_time = round( self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[1]) ) response = client.start_query( logGroupName=self.log_group, startTime=start_time, endTime=end_time, queryString=self.query_string, limit=max_logs, ) return response["queryId"] except client.exceptions.ResourceNotFoundException as e: raise DateOutOfBoundsError(f"Resource not found: {e}")
  • 如需 API 詳細資訊,請參閱《AWS SDK for Python (Boto3) API 參考》中的 StartQuery

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 搭配 AWS SDK 使用 CloudWatch Logs。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。