CloudWatch 儀表板的自訂小工具範例 - Amazon CloudWatch

CloudWatch 儀表板的自訂小工具範例

AWS 可在 JavaScript 和 Python 中提供範本自訂小工具。您可以使用此清單中每個小工具的連結來建立這些範例小工具。或者,您也可以使用 CloudWatch 主控台建立並自訂小工具。此清單中的連結會開啟 AWS CloudFormation 主控台並使用 CloudFormation 快速建立連結建立自訂小工具。

您還可以在 GitHub 上存取自訂小工具範例。

在此清單之後,將顯示每種語言的 Echo 小工具的完整範例。

JavaScript
JavaScript 中的範例自訂小工具
Python
Python 中的範例自訂小工具

JavaScript 中的 Echo 小工具

以下是在 JavaScript 中的 Echo 範例小工具。

const DOCS = ` ## Echo A basic echo script. Anything passed in the \`\`\`echo\`\`\` parameter is returned as the content of the custom widget. ### Widget parameters Param | Description ---|--- **echo** | The content to echo back ### Example parameters \`\`\` yaml echo: <h1>Hello world</h1> \`\`\` `; exports.handler = async (event) => { if (event.describe) { return DOCS; } let widgetContext = JSON.stringify(event.widgetContext, null, 4); widgetContext = widgetContext.replace(/</g, '&lt;'); widgetContext = widgetContext.replace(/>/g, '&gt;'); return `${event.echo || ''}<pre>${widgetContext}</pre>`; };

Python 中的 Echo 小工具

以下是在 Python 中的 Echo 範例小工具。

import json DOCS = """ ## Echo A basic echo script. Anything passed in the ```echo``` parameter is returned as the content of the custom widget. ### Widget parameters Param | Description ---|--- **echo** | The content to echo back ### Example parameters ``` yaml echo: <h1>Hello world</h1> ```""" def lambda_handler(event, context): if 'describe' in event: return DOCS echo = event.get('echo', '') widgetContext = event.get('widgetContext') widgetContext = json.dumps(widgetContext, indent=4) widgetContext = widgetContext.replace('<', '&lt;') widgetContext = widgetContext.replace('>', '&gt;') return f'{echo}<pre>{widgetContext}</pre>'

Java 中的 Echo 小工具

以下是在 Java 中的 Echo 範例小工具。

package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Handler implements RequestHandler<Event, String>{ static String DOCS = "" + "## Echo\n" + "A basic echo script. Anything passed in the ```echo``` parameter is returned as the content of the custom widget.\n" + "### Widget parameters\n" + "Param | Description\n" + "---|---\n" + "**echo** | The content to echo back\n\n" + "### Example parameters\n" + "```yaml\n" + "echo: <h1>Hello world</h1>\n" + "```\n"; Gson gson = new GsonBuilder().setPrettyPrinting().create(); @Override public String handleRequest(Event event, Context context) { if (event.describe) { return DOCS; } return (event.echo != null ? event.echo : "") + "<pre>" + gson.toJson(event.widgetContext) + "</pre>"; } } class Event { public boolean describe; public String echo; public Object widgetContext; public Event() {} public Event(String echo, boolean describe, Object widgetContext) { this.describe = describe; this.echo = echo; this.widgetContext = widgetContext; } }