CloudWatch 使用 f SDK or JavaScript (v3) 记录示例 - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

CloudWatch 使用 f SDK or JavaScript (v3) 记录示例

以下代码示例向您展示了如何使用带 CloudWatch 日志的 AWS SDK for JavaScript (v3) 来执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。

场景是向您展示如何通过在一个服务中调用多个函数或与其他 AWS 服务结合来完成特定任务的代码示例。

每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例演示如何使用 CreateLogGroup

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { CreateLogGroupCommand } from "@aws-sdk/client-cloudwatch-logs"; import { client } from "../libs/client.js"; const run = async () => { const command = new CreateLogGroupCommand({ // The name of the log group. logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP, }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 CreateLogGroup” 中的。

以下代码示例演示如何使用 DeleteLogGroup

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { DeleteLogGroupCommand } from "@aws-sdk/client-cloudwatch-logs"; import { client } from "../libs/client.js"; const run = async () => { const command = new DeleteLogGroupCommand({ // The name of the log group. logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP, }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 DeleteLogGroup” 中的。

以下代码示例演示如何使用 DeleteSubscriptionFilter

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { DeleteSubscriptionFilterCommand } from "@aws-sdk/client-cloudwatch-logs"; import { client } from "../libs/client.js"; const run = async () => { const command = new DeleteSubscriptionFilterCommand({ // The name of the filter. filterName: process.env.CLOUDWATCH_LOGS_FILTER_NAME, // The name of the log group. logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP, }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

以下代码示例演示如何使用 DescribeLogGroups

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { paginateDescribeLogGroups, CloudWatchLogsClient, } from "@aws-sdk/client-cloudwatch-logs"; const client = new CloudWatchLogsClient({}); export const main = async () => { const paginatedLogGroups = paginateDescribeLogGroups({ client }, {}); const logGroups = []; for await (const page of paginatedLogGroups) { if (page.logGroups?.every((lg) => !!lg)) { logGroups.push(...page.logGroups); } } console.log(logGroups); return logGroups; };
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 DescribeLogGroups” 中的。

以下代码示例演示如何使用 DescribeSubscriptionFilters

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { DescribeSubscriptionFiltersCommand } from "@aws-sdk/client-cloudwatch-logs"; import { client } from "../libs/client.js"; const run = async () => { // This will return a list of all subscription filters in your account // matching the log group name. const command = new DescribeSubscriptionFiltersCommand({ logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP, limit: 1, }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

以下代码示例演示如何使用 GetQueryResults

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/** * Simple wrapper for the GetQueryResultsCommand. * @param {string} queryId */ _getQueryResults(queryId) { return this.client.send(new GetQueryResultsCommand({ queryId })); }
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 GetQueryResults” 中的。

以下代码示例演示如何使用 PutSubscriptionFilter

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { PutSubscriptionFilterCommand } from "@aws-sdk/client-cloudwatch-logs"; import { client } from "../libs/client.js"; const run = async () => { const command = new PutSubscriptionFilterCommand({ // An ARN of a same-account Kinesis stream, Kinesis Firehose // delivery stream, or Lambda function. // https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html destinationArn: process.env.CLOUDWATCH_LOGS_DESTINATION_ARN, // A name for the filter. filterName: process.env.CLOUDWATCH_LOGS_FILTER_NAME, // A filter pattern for subscribing to a filtered stream of log events. // https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html filterPattern: process.env.CLOUDWATCH_LOGS_FILTER_PATTERN, // The name of the log group. Messages in this group matching the filter pattern // will be sent to the destination ARN. logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP, }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 PutSubscriptionFilter” 中的。

以下代码示例演示如何使用 StartLiveTail

SDK对于 JavaScript (v3)

包含所需的文件。

import { CloudWatchLogsClient, StartLiveTailCommand } from "@aws-sdk/client-cloudwatch-logs";

处理 Live Tail 会话中的事件。

async function handleResponseAsync(response) { try { for await (const event of response.responseStream) { if (event.sessionStart !== undefined) { console.log(event.sessionStart); } else if (event.sessionUpdate !== undefined) { for (const logEvent of event.sessionUpdate.sessionResults) { const timestamp = logEvent.timestamp; const date = new Date(timestamp); console.log("[" + date + "] " + logEvent.message); } } else { console.error("Unknown event type"); } } } catch (err) { // On-stream exceptions are captured here console.error(err) } }

启动 Live Tail 会话。

const client = new CloudWatchLogsClient(); const command = new StartLiveTailCommand({ logGroupIdentifiers: logGroupIdentifiers, logStreamNames: logStreamNames, logEventFilterPattern: filterPattern }); try{ const response = await client.send(command); handleResponseAsync(response); } catch (err){ // Pre-stream exceptions are captured here console.log(err); }

经过一段时间后停止 Live Tail 会话。

/* Set a timeout to close the client. This will stop the Live Tail session. */ setTimeout(function() { console.log("Client timeout"); client.destroy(); }, 10000);
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 StartLiveTail” 中的。

以下代码示例演示如何使用 StartQuery

SDK对于 JavaScript (v3)
注意

还有更多相关信息 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详细信息,请参阅 “AWS SDK for JavaScript API参考 StartQuery” 中的。

场景

以下代码示例展示了如何使用 CloudWatch 日志查询超过 10,000 条记录。

SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

这是入口点。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { CloudWatchLogsClient } from "@aws-sdk/client-cloudwatch-logs"; import { CloudWatchQuery } from "./cloud-watch-query.js"; console.log("Starting a recursive query..."); if (!process.env.QUERY_START_DATE || !process.env.QUERY_END_DATE) { throw new Error( "QUERY_START_DATE and QUERY_END_DATE environment variables are required.", ); } const cloudWatchQuery = new CloudWatchQuery(new CloudWatchLogsClient({}), { logGroupNames: ["/workflows/cloudwatch-logs/large-query"], dateRange: [ new Date(Number.parseInt(process.env.QUERY_START_DATE)), new Date(Number.parseInt(process.env.QUERY_END_DATE)), ], }); await cloudWatchQuery.run(); console.log( `Queries finished in ${cloudWatchQuery.secondsElapsed} seconds.\nTotal logs found: ${cloudWatchQuery.results.length}`, );

该类可在必要时将查询拆分为多个步骤。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { StartQueryCommand, GetQueryResultsCommand, } from "@aws-sdk/client-cloudwatch-logs"; import { splitDateRange } from "@aws-doc-sdk-examples/lib/utils/util-date.js"; import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js"; class DateOutOfBoundsError extends Error {} export class CloudWatchQuery { /** * Run a query for all CloudWatch Logs within a certain date range. * CloudWatch logs return a max of 10,000 results. This class * performs a binary search across all of the logs in the provided * date range if a query returns the maximum number of results. * * @param {import('@aws-sdk/client-cloudwatch-logs').CloudWatchLogsClient} client * @param {{ logGroupNames: string[], dateRange: [Date, Date], queryConfig: { limit: number } }} config */ constructor(client, { logGroupNames, dateRange, queryConfig }) { this.client = client; /** * All log groups are queried. */ this.logGroupNames = logGroupNames; /** * The inclusive date range that is queried. */ this.dateRange = dateRange; /** * CloudWatch Logs never returns more than 10,000 logs. */ this.limit = queryConfig?.limit ?? 10000; /** * @type {import("@aws-sdk/client-cloudwatch-logs").ResultField[][]} */ this.results = []; } /** * Run the query. */ async run() { this.secondsElapsed = 0; const start = new Date(); this.results = await this._largeQuery(this.dateRange); const end = new Date(); this.secondsElapsed = (end - start) / 1000; return this.results; } /** * Recursively query for logs. * @param {[Date, Date]} dateRange * @returns {Promise<import("@aws-sdk/client-cloudwatch-logs").ResultField[][]>} */ async _largeQuery(dateRange) { const logs = await this._query(dateRange, this.limit); console.log( `Query date range: ${dateRange .map((d) => d.toISOString()) .join(" to ")}. Found ${logs.length} logs.`, ); if (logs.length < this.limit) { return logs; } const lastLogDate = this._getLastLogDate(logs); const offsetLastLogDate = new Date(lastLogDate); offsetLastLogDate.setMilliseconds(lastLogDate.getMilliseconds() + 1); const subDateRange = [offsetLastLogDate, dateRange[1]]; const [r1, r2] = splitDateRange(subDateRange); const results = await Promise.all([ this._largeQuery(r1), this._largeQuery(r2), ]); return [logs, ...results].flat(); } /** * Find the most recent log in a list of logs. * @param {import("@aws-sdk/client-cloudwatch-logs").ResultField[][]} logs */ _getLastLogDate(logs) { const timestamps = logs .map( (log) => log.find((fieldMeta) => fieldMeta.field === "@timestamp")?.value, ) .filter((t) => !!t) .map((t) => `${t}Z`) .sort(); if (!timestamps.length) { throw new Error("No timestamp found in logs."); } return new Date(timestamps[timestamps.length - 1]); } /** * Simple wrapper for the GetQueryResultsCommand. * @param {string} queryId */ _getQueryResults(queryId) { return this.client.send(new GetQueryResultsCommand({ queryId })); } /** * Starts a query and waits for it to complete. * @param {[Date, Date]} dateRange * @param {number} maxLogs */ async _query(dateRange, maxLogs) { try { const { queryId } = await this._startQuery(dateRange, maxLogs); const { results } = await this._waitUntilQueryDone(queryId); return results ?? []; } catch (err) { /** * This error is thrown when StartQuery returns an error indicating * that the query's start or end date occur before the log group was * created. */ if (err instanceof DateOutOfBoundsError) { return []; } throw err; } } /** * 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; } } /** * Call GetQueryResultsCommand until the query is done. * @param {string} queryId */ _waitUntilQueryDone(queryId) { const getResults = async () => { const results = await this._getQueryResults(queryId); const queryDone = [ "Complete", "Failed", "Cancelled", "Timeout", "Unknown", ].includes(results.status); return { queryDone, results }; }; return retry( { intervalInMs: 1000, maxRetries: 60, quiet: true }, async () => { const { queryDone, results } = await getResults(); if (!queryDone) { throw new Error("Query not done."); } return results; }, ); } }