id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
acw-ug-371
acw-ug.pdf
371
Application Signals in your account. If you haven't, see Enable Application Signals in your account. Step 2: Create IAM roles You must create an IAM role. If you already have created this role, you might need to add permissions to it. • ECS task role— Containers use this role to run. The permissions should be whatever your applications need, plus CloudWatchAgentServerPolicy. For more information about creating IAM roles, see Creating IAM Roles. Step 3: Prepare CloudWatch agent configuration First, prepare the agent configuration with Application Signals enabled. To do this, create a local file named /tmp/ecs-cwagent.json. { "traces": { "traces_collected": { "application_signals": {} } }, "logs": { "metrics_collected": { "application_signals": {} } } } Then upload this configuration to the SSM Parameter Store. To do this, enter the following command. In the file, replace $REGION with your actual Region name. Enable your applications on Amazon ECS 1363 Amazon CloudWatch User Guide aws ssm put-parameter \ --name "ecs-cwagent" \ --type "String" \ --value "`cat /tmp/ecs-cwagent.json`" \ --region "$REGION" Step 4: Instrument your application with the CloudWatch agent The next step is to instrument your application for CloudWatch Application Signals. Java To instrument your application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation" } ] 2. Add a CloudWatch agent sidecar definition. To do this, append a new container called ecs- cwagent to your application's task definition. Replace $REGION with your actual Region name. Replace $IMAGE with the path to the latest CloudWatch container image on Amazon Elastic Container Registry. For more information, see cloudwatch-agent on Amazon ECR. If you want to enable the CloudWatch agent with a daemon strategy instead, see the instructions at Deploy using the daemon strategy. { "name": "ecs-cwagent", "image": "$IMAGE", "essential": true, "secrets": [ { "name": "CW_CONFIG_CONTENT", "valueFrom": "ecs-cwagent" } ], "logConfiguration": { Enable your applications on Amazon ECS 1364 Amazon CloudWatch User Guide "logDriver": "awslogs", "options": { "awslogs-create-group": "true", "awslogs-group": "/ecs/ecs-cwagent", "awslogs-region": "$REGION", "awslogs-stream-prefix": "ecs" } } } 3. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "/javaagent.jar", "/otel-auto-instrumentation/javaagent.jar" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "/otel-auto-instrumentation", "readOnly": false } ] } 4. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] Enable your applications on Amazon ECS 1365 Amazon CloudWatch User Guide 5. Add the following environment variables to your application container. You must be using version 1.32.2 or later of the AWS Distro for OpenTelemetry auto-instrumentation agent for Java. Enable your applications on Amazon ECS 1366 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES Specify the following information as key- value pairs: • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. (Optional) To enable log correlation for Application Signals, set an additiona l environment variable aws.log.g roup.names for your application log. By doing so, the to be the log group name traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple Enable your applications on Amazon ECS 1367 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To enable metric environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to none to disable other logs exporters. Set to http/protobuf to send metrics and traces to Application Signals using HTTP. Set to http://localhost:4316/
acw-ug-372
acw-ug.pdf
372
aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To enable metric environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to none to disable other logs exporters. Set to http/protobuf to send metrics and traces to Application Signals using HTTP. Set to http://localhost:4316/ v1/metrics to send metrics to the CloudWatch sidecar. Set to http://localhost:4316/v1/ traces to send traces to the CloudWatc h sidecar. OTEL_AWS_APPLICATION_SIGNAL S_ENABLED OTEL_METRICS_EXPORTER OTEL_LOGS_EXPORTER OTEL_EXPORTER_OTLP_PROTOCOL OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT OTEL_EXPORTER_OTLP_TRACES_E NDPOINT Enable your applications on Amazon ECS 1368 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_TRACES_SAMPLER Set this to xray to set X-Ray as the traces sampler. OTEL_PROPAGATORS Set xray as one of the propagators. JAVA_TOOL_OPTIONS Set to " -javaagent:$ AWS_ADOT_ JAVA_INSTRUMENTATION_PATH Replace AWS_ADOT_JAVA_INST " RUMENTATION_PATH where the AWS Distro for OpenTelemetry with the path Java auto-instrumentation agent is stored. For example, /otel-auto-instrum entation/javaagent.jar 6. Mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. If you don't need to enable log correlation with metrics and traces, use the following example for a Java application. If you want to enable log correlation, see the next step instead. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, Enable your applications on Amazon ECS 1369 Amazon CloudWatch { User Guide "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "JAVA_TOOL_OPTIONS", "value": " -javaagent:/otel-auto-instrumentation/javaagent.jar" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://localhost:4316/v1/traces" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_PROPAGATORS", "value": "tracecontext,baggage,b3,xray" } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "/otel-auto-instrumentation", "readOnly": false } ] } Enable your applications on Amazon ECS 1370 Amazon CloudWatch Python User Guide Before you enable Application Signals for your Python applications, be aware of the following considerations. • In some containerized applications, a missing PYTHONPATH environment variable can sometimes cause the application to fail to start. To resolve this, ensure that you set the PYTHONPATH environment variable to the location of your application’s working directory. This is due to a known issue with OpenTelemetry auto-instrumentation. For more information about this issue, see Python autoinstrumentation setting of PYTHONPATH is not compliant. • For Django applications, there are additional required configurations, which are outlined in the OpenTelemetry Python documentation. • Use the --noreload flag to prevent automatic reloading. • Set the DJANGO_SETTINGS_MODULE environment variable to the location of your Django application’s settings.py file. This ensures that OpenTelemetry can correctly access and integrate with your Django settings. • If you're using a WSGI server for your Python application, in addition to the following steps in this section, see No Application Signals data for Python application that uses a WSGI server for information to make Application Signals work. To instrument your Python application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation-python" } ] 2. Add a CloudWatch agent sidecar definition. To do this, append a new container called ecs- cwagent to your application's task definition. Replace $REGION with your actual Region name. Replace $IMAGE with the path to the latest CloudWatch container image on Amazon Elastic Container Registry. For more information, see cloudwatch-agent on Amazon ECR. If you want to enable the CloudWatch agent with a daemon strategy instead, see the instructions at Deploy using the daemon strategy. Enable your applications on Amazon ECS 1371 Amazon CloudWatch User Guide { "name": "ecs-cwagent", "image": "$IMAGE", "essential": true, "secrets": [ { "name": "CW_CONFIG_CONTENT", "valueFrom": "ecs-cwagent" } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-create-group": "true", "awslogs-group": "/ecs/ecs-cwagent", "awslogs-region": "$REGION", "awslogs-stream-prefix": "ecs" } } } 3. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "-a", "/autoinstrumentation/.", "/otel-auto-instrumentation-python" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-python", "containerPath": "/otel-auto-instrumentation-python", "readOnly": false } ] } Enable your applications on Amazon ECS 1372 Amazon CloudWatch User Guide 4. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 5. Add the following environment variables to your application container. Environment variable Setting
acw-ug-373
acw-ug.pdf
373
to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "-a", "/autoinstrumentation/.", "/otel-auto-instrumentation-python" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-python", "containerPath": "/otel-auto-instrumentation-python", "readOnly": false } ] } Enable your applications on Amazon ECS 1372 Amazon CloudWatch User Guide 4. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 5. Add the following environment variables to your application container. Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES Specify the following information as key- value pairs: • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. (Optional) To enable log correlation for Application Signals, set an additiona Enable your applications on Amazon ECS 1373 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals l environment variable aws.log.g to be the log group name roup.names for your application log. By doing so, the traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To enable metric environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to http/protobuf to send metrics and traces to CloudWatch using HTTP. Set to http://127.0.0.1:4316/ v1/metrics to send metrics to the CloudWatch sidecar. OTEL_AWS_APPLICATION_SIGNAL S_ENABLED OTEL_METRICS_EXPORTER OTEL_EXPORTER_OTLP_PROTOCOL OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT Enable your applications on Amazon ECS 1374 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_EXPORTER_OTLP_TRACES_E NDPOINT OTEL_TRACES_SAMPLER Set to http://127.0.0.1:4316/v1/ traces to send traces to the CloudWatc h sidecar. Set this to xray to set X-Ray as the traces sampler. OTEL_PROPAGATORS Add xray as one of the propagators. OTEL_PYTHON_DISTRO OTEL_PYTHON_CONFIGURATOR PYTHONPATH DJANGO_SETTINGS_MODULE Set to aws_distro to use the ADOT Python instrumentation. Set to aws_configurator to use the ADOT Python configuration. Replace $APP_PATH with the location of the application’s working directory within the container. This is required for the Python interpreter to find your application modules. Required only for Django applications. Set it to the location of your Django application’s settings.py file. Replace $PATH_TO_SETTINGS . 6. Mount the volume opentelemetry-auto-instrumentation-python that you defined in step 1 of this procedure. If you don't need to enable log correlation with metrics and traces, use the following example for a Python application. If you want to enable log correlation, see the next step instead. { "name": "my-app", ... "environment": [ { "name": "PYTHONPATH", Enable your applications on Amazon ECS 1375 Amazon CloudWatch User Guide "value": "/otel-auto-instrumentation-python/opentelemetry/instrumentation/ auto_instrumentation:$APP_PATH:/otel-auto-instrumentation-python" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://localhost:2000" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_PYTHON_DISTRO", "value": "aws_distro" }, { "name": "OTEL_PYTHON_CONFIGURATOR", "value": "aws_configurator" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://localhost:4316/v1/traces" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { Enable your applications on Amazon ECS 1376 Amazon CloudWatch User Guide "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "DJANGO_SETTINGS_MODULE", "value": "$PATH_TO_SETTINGS.settings" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-python", "containerPath": "/otel-auto-instrumentation-python", "readOnly": false } ] } 7. (Optional) To enable log correlation, do the following before you mount the volume. In OTEL_RESOURCE_ATTRIBUTES, set an additional environment variable aws.log.group.names for the log groups of your application. By doing so, the traces and metrics from your application can be correlated with the relevant log entries from these log groups. For this variable, replace $YOUR_APPLICATION_LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-group-1&log- group-2. To enable metric to log correlation, setting this current environmental variable is enough. For more information,
acw-ug-374
acw-ug.pdf
374
(Optional) To enable log correlation, do the following before you mount the volume. In OTEL_RESOURCE_ATTRIBUTES, set an additional environment variable aws.log.group.names for the log groups of your application. By doing so, the traces and metrics from your application can be correlated with the relevant log entries from these log groups. For this variable, replace $YOUR_APPLICATION_LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-group-1&log- group-2. To enable metric to log correlation, setting this current environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. The following is an example. To enable log correlation, use this example when you mount the volume opentelemetry-auto-instrumentation-python that you defined in step 1 of this procedure. { "name": "my-app", ... "environment": [ { "name": "PYTHONPATH", "value": "/otel-auto-instrumentation-python/opentelemetry/instrumentation/ auto_instrumentation:$APP_PATH:/otel-auto-instrumentation-python" Enable your applications on Amazon ECS 1377 Amazon CloudWatch }, User Guide { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://localhost:2000" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_PYTHON_DISTRO", "value": "aws_distro" }, { "name": "OTEL_PYTHON_CONFIGURATOR", "value": "aws_configurator" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://localhost:4316/v1/traces" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", Enable your applications on Amazon ECS 1378 Amazon CloudWatch "value": User Guide "aws.log.group.names=$YOUR_APPLICATION_LOG_GROUP,service.name=$SVC_NAME" }, { "name": "DJANGO_SETTINGS_MODULE", "value": "$PATH_TO_SETTINGS.settings" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-python", "containerPath": "/otel-auto-instrumentation-python", "readOnly": false } ] } .NET To instrument your application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation" } ] 2. Add a CloudWatch agent sidecar definition. To do this, append a new container called ecs- cwagent to your application's task definition. Replace $REGION with your actual Region name. Replace $IMAGE with the path to the latest CloudWatch container image on Amazon Elastic Container Registry. For more information, see cloudwatch-agent on Amazon ECR. If you want to enable the CloudWatch agent with a daemon strategy instead, see the instructions at Deploy using the daemon strategy. { "name": "ecs-cwagent", "image": "$IMAGE", Enable your applications on Amazon ECS 1379 Amazon CloudWatch User Guide "essential": true, "secrets": [ { "name": "CW_CONFIG_CONTENT", "valueFrom": "ecs-cwagent" } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-create-group": "true", "awslogs-group": "/ecs/ecs-cwagent", "awslogs-region": "$REGION", "awslogs-stream-prefix": "ecs" } } } 3. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. For a Linux container instance, use the following. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "-a", "autoinstrumentation/.", "/otel-auto-instrumentation" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "/otel-auto-instrumentation", "readOnly": false } ] } For a Windows Server container instance, use the following. Enable your applications on Amazon ECS 1380 Amazon CloudWatch User Guide { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "CMD", "/c", "xcopy", "/e", "C:\\autoinstrumentation\\*", "C:\\otel-auto-instrumentation", "&&", "icacls", "C:\\otel-auto-instrumentation", "/grant", "*S-1-1-0:R", "/T" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "C:\\otel-auto-instrumentation", "readOnly": false } ] } 4. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 5. Add the following environment variables to your application container. You must be using version 1.1.0 or later of the AWS Distro for OpenTelemetry auto-instrumentation agent for .NET. Enable your applications on Amazon ECS 1381 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES OTEL_AWS_APPLICATION_SIGNAL S_ENABLED OTEL_METRICS_EXPORTER OTEL_LOGS_EXPORTER Specify the following information as key- value pairs: • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to none to disable other logs exporters. Enable your applications on Amazon ECS 1382 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_EXPORTER_OTLP_PROTOCOL OTEL_AWS_APPLICATION_SIGNAL
acw-ug-375
acw-ug.pdf
375
be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to none to disable other logs exporters. Enable your applications on Amazon ECS 1382 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_EXPORTER_OTLP_PROTOCOL OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT OTEL_EXPORTER_OTLP_ENDPOINT OTEL_EXPORTER_OTLP_TRACES_E NDPOINT OTEL_DOTNET_AUTO_HOME Set to http/protobuf to send metrics and traces to Application Signals using HTTP. Set to http://localhost:4316/ v1/metrics to send metrics to the CloudWatch sidecar. Set to http://localhost:4316/ to send traces to the CloudWatch sidecar. Set to http://localhost:4316/v1/ traces to send traces to the CloudWatc h sidecar. Set to the installation location of ADOT .NET automatic instrumentation. OTEL_DOTNET_AUTO_PLUGINS Set to AWS.Distro.OpenTel emetry.AutoInstrumentation. Plugin, AWS.Distro.OpenTel emetry.AutoInstrumentation enable the Application Signals plugin. to CORECLR_ENABLE_PROFILING Set to 1 to enable the profiler. CORECLR_PROFILER Set to {918728DD-259F-4A6A-AC2B- as the CLSID of the B85E1B658318} profiler. Enable your applications on Amazon ECS 1383 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals CORECLR_PROFILER_PATH Set this to the path of the profiler. On Linux, set it to ${OTEL_DO TNET_AUTO_HOME}/linux-x64/O penTelemetry.AutoInstrument ation.Native.so On Windows Server, set it to ${OTEL_DO TNET_AUTO_HOME}/win-x64/Ope nTelemetry.AutoInstrumentat ion.Native.dll DOTNET_ADDITIONAL_DEPS Set this to the folder path of ${OTEL_DO TNET_AUTO_HOME}/AdditionalD eps . DOTNET_SHARED_STORE Set this to the folder path of ${OTEL_DO TNET_AUTO_HOME}/store . DOTNET_STARTUP_HOOKS Set this to path of the managed assembly ${OTEL_DOTNET_AUTO_HOME}/ne t/OpenTelemetry.AutoInstrum entation.StartupHook.dll before the main application's entry point. to run 6. Mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. For Linux, use the following. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "CORECLR_ENABLE_PROFILING", Enable your applications on Amazon ECS 1384 Amazon CloudWatch User Guide "value": "1" }, { "name": "CORECLR_PROFILER", "value": "{918728DD-259F-4A6A-AC2B-B85E1B658318}" }, { "name": "CORECLR_PROFILER_PATH", "value": "/otel-auto-instrumentation/linux-x64/ OpenTelemetry.AutoInstrumentation.Native.so" }, { "name": "DOTNET_ADDITIONAL_DEPS", "value": "/otel-auto-instrumentation/AdditionalDeps" }, { "name": "DOTNET_SHARED_STORE", "value": "/otel-auto-instrumentation/store" }, { "name": "DOTNET_STARTUP_HOOKS", "value": "/otel-auto-instrumentation/net/ OpenTelemetry.AutoInstrumentation.StartupHook.dll" }, { "name": "OTEL_DOTNET_AUTO_HOME", "value": "/otel-auto-instrumentation" }, { "name": "OTEL_DOTNET_AUTO_PLUGINS", "value": "AWS.Distro.OpenTelemetry.AutoInstrumentation.Plugin, AWS.Distro.OpenTelemetry.AutoInstrumentation" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "aws.log.group.names= $YOUR_APPLICATION_LOG_GROUP,service.name=aws-dotnet-service-name" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", Enable your applications on Amazon ECS 1385 Amazon CloudWatch User Guide "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://localhost:4316/v1/traces" }, { "name": "OTEL_EXPORTER_OTLP_ENDPOINT", "value": "http://localhost:4316" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://localhost:2000" }, { "name": "OTEL_PROPAGATORS", "value": "tracecontext,baggage,b3,xray" } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", Enable your applications on Amazon ECS 1386 Amazon CloudWatch User Guide "containerPath": "/otel-auto-instrumentation", "readOnly": false } ] } For Windows Server, use the following. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "CORECLR_ENABLE_PROFILING", "value": "1" }, { "name": "CORECLR_PROFILER", "value": "{918728DD-259F-4A6A-AC2B-B85E1B658318}" }, { "name": "CORECLR_PROFILER_PATH", "value": "C:\\otel-auto-instrumentation\\win-x64\ \OpenTelemetry.AutoInstrumentation.Native.dll" }, { "name": "DOTNET_ADDITIONAL_DEPS", "value": "C:\\otel-auto-instrumentation\\AdditionalDeps" }, { "name": "DOTNET_SHARED_STORE", "value": "C:\\otel-auto-instrumentation\\store" }, { "name": "DOTNET_STARTUP_HOOKS", "value": "C:\\otel-auto-instrumentation\\net\ \OpenTelemetry.AutoInstrumentation.StartupHook.dll" }, { Enable your applications on Amazon ECS 1387 Amazon CloudWatch User Guide "name": "OTEL_DOTNET_AUTO_HOME", "value": "C:\\otel-auto-instrumentation" }, { "name": "OTEL_DOTNET_AUTO_PLUGINS", "value": "AWS.Distro.OpenTelemetry.AutoInstrumentation.Plugin, AWS.Distro.OpenTelemetry.AutoInstrumentation" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "aws.log.group.names= $YOUR_APPLICATION_LOG_GROUP,service.name=dotnet-service-name" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://localhost:4316/v1/traces" }, { "name": "OTEL_EXPORTER_OTLP_ENDPOINT", "value": "http://localhost:4316" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" Enable your applications on Amazon ECS 1388 Amazon CloudWatch }, User Guide { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://localhost:2000" }, { "name": "OTEL_PROPAGATORS", "value": "tracecontext,baggage,b3,xray" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "C:\\otel-auto-instrumentation", "readOnly": false } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] } Node.js Note If you are enabling Application Signals for a Node.js application with ESM, see Setting up a Node.js application with the ESM module format before you start these steps. To instrument your application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation-node" Enable your applications on Amazon ECS 1389 Amazon CloudWatch } ] User Guide 2. Add a CloudWatch agent sidecar definition. To do this, append a new container called ecs- cwagent to your application's task definition. Replace $REGION with your actual Region name. Replace $IMAGE with the path to the latest CloudWatch container image on Amazon Elastic Container
acw-ug-376
acw-ug.pdf
376
application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation-node" Enable your applications on Amazon ECS 1389 Amazon CloudWatch } ] User Guide 2. Add a CloudWatch agent sidecar definition. To do this, append a new container called ecs- cwagent to your application's task definition. Replace $REGION with your actual Region name. Replace $IMAGE with the path to the latest CloudWatch container image on Amazon Elastic Container Registry. For more information, see cloudwatch-agent on Amazon ECR. If you want to enable the CloudWatch agent with a daemon strategy instead, see the instructions at Deploy using the daemon strategy. { "name": "ecs-cwagent", "image": "$IMAGE", "essential": true, "secrets": [ { "name": "CW_CONFIG_CONTENT", "valueFrom": "ecs-cwagent" } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-create-group": "true", "awslogs-group": "/ecs/ecs-cwagent", "awslogs-region": "$REGION", "awslogs-stream-prefix": "ecs" } } } 3. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "-a", Enable your applications on Amazon ECS 1390 Amazon CloudWatch User Guide "/autoinstrumentation/.", "/otel-auto-instrumentation-node" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-node", "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } ], } 4. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 5. Add the following environment variables to your application container. Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES Specify the following information as key- value pairs: • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. Enable your applications on Amazon ECS 1391 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. (Optional) To enable log correlation for Application Signals, set an additiona l environment variable aws.log.g roup.names for your application log. By doing so, the to be the log group name traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To enable metric environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. OTEL_AWS_APPLICATION_SIGNAL S_ENABLED Enable your applications on Amazon ECS 1392 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_METRICS_EXPORTER OTEL_LOGS_EXPORTER OTEL_EXPORTER_OTLP_PROTOCOL OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT OTEL_EXPORTER_OTLP_TRACES_E NDPOINT OTEL_TRACES_SAMPLER Set to none to disable other metrics exporters. Set to none to disable other logs exporters. Set to http/protobuf to send metrics and traces to Application Signals using OTLP/HTTP and protobuf. Set to http://localhost:4316/ v1/metrics to send metrics to the CloudWatch sidecar. Set to http://localhost:4316/v1/ traces to send traces to the CloudWatc h sidecar. Set this to xray to set X-Ray as the traces sampler. OTEL_PROPAGATORS Set xray as one of the propagators. NODE_OPTIONS Set to --require AWS_ADOT_ NODE_INSTRUMENTATION_PATH Replace AWS_ADOT_NODE_INST . RUMENTATION_PATH where the AWS Distro for OpenTelemetry with the path Node.js auto-instrumentation is stored. For example, /otel-auto-instrum entation-node/autoinstrumen tation.js 6. Mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. If you don't need to enable log correlation with metrics and traces, use the following example for a Node.js application. If you want to enable log correlation, see the next step instead. Enable your applications on Amazon ECS 1393 Amazon CloudWatch User Guide For your Application Container, add a dependency on the init container to make sure that container finishes before your application container starts. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name":
acw-ug-377
acw-ug.pdf
377
metrics and traces, use the following example for a Node.js application. If you want to enable log correlation, see the next step instead. Enable your applications on Amazon ECS 1393 Amazon CloudWatch User Guide For your Application Container, add a dependency on the init container to make sure that container finishes before your application container starts. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://localhost:4316/v1/traces" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://localhost:2000" Enable your applications on Amazon ECS 1394 Amazon CloudWatch }, { "name": "NODE_OPTIONS", "value": "--require /otel-auto-instrumentation-node/ User Guide autoinstrumentation.js" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-node", "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] } 7. (Optional) To enable log correlation, do the following before you mount the volume. In OTEL_RESOURCE_ATTRIBUTES, set an additional environment variable aws.log.group.names for the log groups of your application. By doing so, the traces and metrics from your application can be correlated with the relevant log entries from these log groups. For this variable, replace $YOUR_APPLICATION_LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-group-1&log- group-2. To enable metric to log correlation, setting this current environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. The following is an example. Use this example to enable log correlation when you mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. { "name": "my-app", ... Enable your applications on Amazon ECS 1395 Amazon CloudWatch User Guide "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "aws.log.group.names=$YOUR_APPLICATION_LOG_GROUP,service.name=$SVC_NAME" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://localhost:4316/v1/traces" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://localhost:2000" }, { "name": "NODE_OPTIONS", "value": "--require /otel-auto-instrumentation-node/ autoinstrumentation.js" } ], Enable your applications on Amazon ECS 1396 Amazon CloudWatch "mountPoints": [ User Guide { "sourceVolume": "opentelemetry-auto-instrumentation-node", "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] } Setting up a Node.js application with the ESM module format We provide limited support for Node.js applications with the ESM module format. For details, see the section called “Known limitations about Node.js with ESM”. For the ESM module format, using the init container to inject the Node.js instrumentation SDK doesn’t apply. To enable Application Signals for Node.js with ESM, skip steps 1 and 3 of the previous procedure, and do the following instead. To enable Application Signals for a Node.js application with ESM 1. Install the relevant dependencies to your Node.js application for autoinstrumentation: npm install @aws/aws-distro-opentelemetry-node-autoinstrumentation npm install @opentelemetry/instrumentation@0.54.0 2. In steps 5 and 6 in the previous procedure, remove the mounting of the volume opentelemetry-auto-instrumentation-node: "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-node", "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } Enable your applications on Amazon ECS 1397 Amazon CloudWatch ] User Guide Replace the node options with the following. { "name": "NODE_OPTIONS", "value": "--import @aws/aws-distro-opentelemetry-node-autoinstrumentation/ register --experimental-loader=@opentelemetry/instrumentation/hook.mjs" } Step 5: Deploy your application Create a new revision of your task definition and deploy it to your application cluster. You should see three containers in the newly created task: • init– A required container for initializing Application Signals. • ecs-cwagent– A container running the CloudWatch agent • my-app– This is the example application container in our documentation. In your actual workloads, this specific container might not exist or might be replaced with your own service containers. (Optional) Step 6: Monitor your application health Once you have enabled your applications on Amazon ECS, you can monitor your application health. For more information, see Monitor the operational health of your applications with Application Signals. Deploy using the daemon strategy Step 1: Enable Application Signals in your account You must first enable Application Signals in your account. If you haven't, see Enable Application Signals in your account. Step 2: Create IAM roles You must create an IAM role. If you already have created this role, you might need to add permissions to it. Enable your applications on Amazon ECS 1398 Amazon CloudWatch User Guide • ECS task role— Containers use this role to run. The permissions should be whatever your applications need, plus CloudWatchAgentServerPolicy. For more information about creating IAM roles, see Creating IAM Roles. Step 3: Prepare
acw-ug-378
acw-ug.pdf
378
daemon strategy Step 1: Enable Application Signals in your account You must first enable Application Signals in your account. If you haven't, see Enable Application Signals in your account. Step 2: Create IAM roles You must create an IAM role. If you already have created this role, you might need to add permissions to it. Enable your applications on Amazon ECS 1398 Amazon CloudWatch User Guide • ECS task role— Containers use this role to run. The permissions should be whatever your applications need, plus CloudWatchAgentServerPolicy. For more information about creating IAM roles, see Creating IAM Roles. Step 3: Prepare CloudWatch agent configuration First, prepare the agent configuration with Application Signals enabled. To do this, create a local file named /tmp/ecs-cwagent.json. { "traces": { "traces_collected": { "application_signals": {} } }, "logs": { "metrics_collected": { "application_signals": {} } } } Then upload this configuration to the SSM Parameter Store. To do this, enter the following command. In the file, replace $REGION with your actual Region name. aws ssm put-parameter \ --name "ecs-cwagent" \ --type "String" \ --value "`cat /tmp/ecs-cwagent.json`" \ --region "$REGION" Step 4: Deploy the CloudWatch agent daemon service Create the following task definition and deploy it to your application cluster. Replace $REGION with your actual Region name. Replace $TASK_ROLE_ARN and $EXECUTION_ROLE_ARN with the IAM roles you prepared in Step 2: Create IAM roles. Replace $IMAGE with the path to the latest CloudWatch container image on Amazon Elastic Container Registry. For more information, see cloudwatch-agent on Amazon ECR. Enable your applications on Amazon ECS 1399 Amazon CloudWatch Note User Guide The daemon service exposes two ports on the host, with 4316 used as endpoint for receiving metrics and traces and 2000 as the CloudWatch trace sampler endpoint. This setup allows the agent to collect and transmit telemetry data from all application tasks running on the host. Ensure that these ports are not used by other services on the host to avoid conflicts. { "family": "ecs-cwagent-daemon", "taskRoleArn": "$TASK_ROLE_ARN", "executionRoleArn": "$EXECUTION_ROLE_ARN", "networkMode": "bridge", "containerDefinitions": [ { "name": "ecs-cwagent", "image": "$IMAGE", "essential": true, "portMappings": [ { "containerPort": 4316, "hostPort": 4316 }, { "containerPort": 2000, "hostPort": 2000 } ], "secrets": [ { "name": "CW_CONFIG_CONTENT", "valueFrom": "ecs-cwagent" } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-create-group": "true", "awslogs-group": "/ecs/ecs-cwagent", "awslogs-region": "$REGION", "awslogs-stream-prefix": "ecs" Enable your applications on Amazon ECS 1400 User Guide Amazon CloudWatch } } } ], "requiresCompatibilities": [ "EC2" ], "cpu": "128", "memory": "64" } Step 5: Instrument your application The next step is to instrument your application for Application Signals. Java To instrument your application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation" } ] 2. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "/javaagent.jar", "/otel-auto-instrumentation/javaagent.jar" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", Enable your applications on Amazon ECS 1401 Amazon CloudWatch User Guide "containerPath": "/otel-auto-instrumentation", "readOnly": false } ] } 3. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 4. Add the following environment variables to your application container. You must be using version 1.32.2 or later of the AWS Distro for OpenTelemetry auto-instrumentation agent for Java. Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES Specify the following information as key- value pairs: • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. Enable your applications on Amazon ECS 1402 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. (Optional) To enable log correlation for Application Signals, set an additiona l environment variable aws.log.g roup.names for your application log. By doing so, the to be the log group name traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example:
acw-ug-379
acw-ug.pdf
379
is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. (Optional) To enable log correlation for Application Signals, set an additiona l environment variable aws.log.g roup.names for your application log. By doing so, the to be the log group name traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To enable metric environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. OTEL_AWS_APPLICATION_SIGNAL S_ENABLED Enable your applications on Amazon ECS 1403 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_METRICS_EXPORTER OTEL_LOGS_EXPORTER OTEL_EXPORTER_OTLP_PROTOCOL Set to none to disable other metrics exporters. Set to none to disable other logs exporters. Set to http/protobuf to send metrics and traces to Application Signals using HTTP. OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT Sends metrics to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316/v1/metrics . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ metrics, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). Enable your applications on Amazon ECS 1404 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_EXPORTER_OTLP_TRACES_E NDPOINT Sends traces to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316/v1/traces . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ traces, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). Set this to xray to set X-Ray as the traces sampler. OTEL_TRACES_SAMPLER OTEL_PROPAGATORS Set xray as one of the propagators. JAVA_TOOL_OPTIONS Set to " -javaagent:$ AWS_ADOT_ JAVA_INSTRUMENTATION_PATH Replace AWS_ADOT_JAVA_INST " RUMENTATION_PATH where the AWS Distro for OpenTelemetry with the path Java auto-instrumentation agent is stored. For example, /otel-auto-instrum entation/javaagent.jar 5. Mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. If you don't need to enable log correlation with metrics and traces, use the following example for a Java application. If you want to enable log correlation, see the next step instead. { "name": "my-app", Enable your applications on Amazon ECS 1405 Amazon CloudWatch User Guide ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "JAVA_TOOL_OPTIONS", "value": " -javaagent:/otel-auto-instrumentation/javaagent.jar" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/traces" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_PROPAGATORS", "value": "tracecontext,baggage,b3,xray" } ], "dependsOn": [ Enable your applications on Amazon ECS 1406 Amazon CloudWatch { "containerName": "init", "condition": "SUCCESS" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "/otel-auto-instrumentation", "readOnly": false User Guide } ] } Python Before you enable Application Signals for your Python applications, be aware of the following considerations. • In some containerized applications, a missing PYTHONPATH environment variable can sometimes cause the application to fail to start. To resolve this, ensure that you set the PYTHONPATH environment variable to the location of your application’s working directory. This is due to a known issue with OpenTelemetry auto-instrumentation. For more information about this issue, see Python autoinstrumentation setting of PYTHONPATH is not compliant. • For Django applications, there are additional required configurations, which are outlined in the OpenTelemetry Python documentation. • Use the --noreload flag to prevent automatic reloading. • Set the DJANGO_SETTINGS_MODULE environment variable to the location of your Django application’s settings.py file. This ensures that OpenTelemetry can correctly access and integrate with your Django settings. • If you're using a WSGI server for your Python application, in addition to the following steps in this section, see No Application Signals data for Python application that uses a WSGI server for information to make Application Signals work. To instrument your Python application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. Enable your applications on Amazon ECS 1407 Amazon CloudWatch User Guide "volumes": [ { "name": "opentelemetry-auto-instrumentation-python" } ] 2.
acw-ug-380
acw-ug.pdf
380
If you're using a WSGI server for your Python application, in addition to the following steps in this section, see No Application Signals data for Python application that uses a WSGI server for information to make Application Signals work. To instrument your Python application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. Enable your applications on Amazon ECS 1407 Amazon CloudWatch User Guide "volumes": [ { "name": "opentelemetry-auto-instrumentation-python" } ] 2. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "-a", "/autoinstrumentation/.", "/otel-auto-instrumentation-python" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-python", "containerPath": "/otel-auto-instrumentation-python", "readOnly": false } ] } 3. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 4. Add the following environment variables to your application container. Enable your applications on Amazon ECS 1408 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES Specify the following information as key- value pairs: • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. (Optional) To enable log correlation for Application Signals, set an additiona l environment variable aws.log.g roup.names for your application log. By doing so, the to be the log group name traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple Enable your applications on Amazon ECS 1409 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To enable metric environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to http/protobuf to send metrics and traces to CloudWatch using HTTP. OTEL_AWS_APPLICATION_SIGNAL S_ENABLED OTEL_METRICS_EXPORTER OTEL_EXPORTER_OTLP_PROTOCOL Enable your applications on Amazon ECS 1410 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT Sends metrics to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316/v1/metrics . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ metrics, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). OTEL_EXPORTER_OTLP_TRACES_E NDPOINT Sends traces to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316/v1/traces . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ traces, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). Set this to xray to set X-Ray as the traces sampler. OTEL_TRACES_SAMPLER Enable your applications on Amazon ECS 1411 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_TRACES_SAMPLER_ARG Sets the traces sampler endpoint. • For applications running in host mode, set this to http://localhost:2 000 . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :2000, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). OTEL_PROPAGATORS Add xray as one of the propagators. OTEL_PYTHON_DISTRO OTEL_PYTHON_CONFIGURATOR PYTHONPATH DJANGO_SETTINGS_MODULE Set to aws_distro to use the ADOT Python instrumentation. Set to aws_configuration to use the ADOT Python configuration. Replace $APP_PATH with the location of the application’s working directory within the container. This is required for the Python interpreter to find your application modules. Required only for Django applications. Set it to the location of
acw-ug-381
acw-ug.pdf
381
in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :2000, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). OTEL_PROPAGATORS Add xray as one of the propagators. OTEL_PYTHON_DISTRO OTEL_PYTHON_CONFIGURATOR PYTHONPATH DJANGO_SETTINGS_MODULE Set to aws_distro to use the ADOT Python instrumentation. Set to aws_configuration to use the ADOT Python configuration. Replace $APP_PATH with the location of the application’s working directory within the container. This is required for the Python interpreter to find your application modules. Required only for Django applications. Set it to the location of your Django application’s settings.py file. Replace $PATH_TO_SETTINGS . 5. Mount the volume opentelemetry-auto-instrumentation-python that you defined in step 1 of this procedure. If you don't need to enable log correlation with metrics and Enable your applications on Amazon ECS 1412 Amazon CloudWatch User Guide traces, use the following example for a Python application. If you want to enable log correlation, see the next step instead. { "name": "my-app", ... "environment": [ { "name": "PYTHONPATH", "value": "/otel-auto-instrumentation-python/opentelemetry/instrumentation/ auto_instrumentation:$APP_PATH:/otel-auto-instrumentation-python" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://CW_CONTAINER_IP:2000" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_PYTHON_DISTRO", "value": "aws_distro" }, { "name": "OTEL_PYTHON_CONFIGURATOR", "value": "aws_configurator" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/traces" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/metrics" Enable your applications on Amazon ECS 1413 Amazon CloudWatch }, User Guide { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "DJANGO_SETTINGS_MODULE", "value": "$PATH_TO_SETTINGS.settings" } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-python", "containerPath": "/otel-auto-instrumentation-python", "readOnly": false } ] } 6. (Optional) To enable log correlation, do the following before you mount the volume. In OTEL_RESOURCE_ATTRIBUTES, set an additional environment variable aws.log.group.names for the log groups of your application. By doing so, the traces and metrics from your application can be correlated with the relevant log entries from these log groups. For this variable, replace $YOUR_APPLICATION_LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-group-1&log- group-2. To enable metric to log correlation, setting this current environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to Enable your applications on Amazon ECS 1414 Amazon CloudWatch User Guide log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. The following is an example. To enable log correlation, use this example when you mount the volume opentelemetry-auto-instrumentation-python that you defined in step 1 of this procedure. { "name": "my-app", ... "environment": [ { "name": "PYTHONPATH", "value": "/otel-auto-instrumentation-python/opentelemetry/instrumentation/ auto_instrumentation:$APP_PATH:/otel-auto-instrumentation-python" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://CW_CONTAINER_IP:2000" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_PYTHON_DISTRO", "value": "aws_distro" }, { "name": "OTEL_PYTHON_CONFIGURATOR", "value": "aws_configurator" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/traces" Enable your applications on Amazon ECS 1415 Amazon CloudWatch }, User Guide { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/metrics" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "aws.log.group.names=$YOUR_APPLICATION_LOG_GROUP,service.name=$SVC_NAME" }, { "name": "DJANGO_SETTINGS_MODULE", "value": "$PATH_TO_SETTINGS.settings" } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-python", "containerPath": "/otel-auto-instrumentation-python", "readOnly": false } ] } Enable your applications on Amazon ECS 1416 Amazon CloudWatch .NET User Guide To instrument your application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation" } ] 2. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. For a Linux container instance, use the following. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "-a", "autoinstrumentation/.", "/otel-auto-instrumentation" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "/otel-auto-instrumentation", "readOnly": false } ] } For a Windows Server container instance, use the following. { "name": "init", "image": "$IMAGE", Enable your applications on Amazon ECS 1417 Amazon CloudWatch User Guide "essential": false, "command": [ "CMD", "/c", "xcopy", "/e", "C:\\autoinstrumentation\\*", "C:\\otel-auto-instrumentation", "&&", "icacls", "C:\\otel-auto-instrumentation", "/grant", "*S-1-1-0:R", "/T" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "C:\\otel-auto-instrumentation", "readOnly": false } ] } 3. Add a dependency on the init container to make sure that container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 4. Add the following environment variables to your application container. You must be using version 1.1.0 or later of the AWS Distro for OpenTelemetry auto-instrumentation
acw-ug-382
acw-ug.pdf
382
the following. { "name": "init", "image": "$IMAGE", Enable your applications on Amazon ECS 1417 Amazon CloudWatch User Guide "essential": false, "command": [ "CMD", "/c", "xcopy", "/e", "C:\\autoinstrumentation\\*", "C:\\otel-auto-instrumentation", "&&", "icacls", "C:\\otel-auto-instrumentation", "/grant", "*S-1-1-0:R", "/T" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "C:\\otel-auto-instrumentation", "readOnly": false } ] } 3. Add a dependency on the init container to make sure that container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 4. Add the following environment variables to your application container. You must be using version 1.1.0 or later of the AWS Distro for OpenTelemetry auto-instrumentation agent for .NET. Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES Specify the following information as key- value pairs: Enable your applications on Amazon ECS 1418 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to none to disable other logs exporters. Set to http/protobuf to send metrics and traces to Application Signals using HTTP. OTEL_AWS_APPLICATION_SIGNAL S_ENABLED OTEL_METRICS_EXPORTER OTEL_LOGS_EXPORTER OTEL_EXPORTER_OTLP_PROTOCOL Enable your applications on Amazon ECS 1419 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT Sends metrics to the CloudWatch daemon container. OTEL_EXPORTER_OTLP_ENDPOINT • For applications running in host mode, set this to http://localhost:4 316/v1/metrics . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ metrics, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). Sends traces to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316 . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). Enable your applications on Amazon ECS 1420 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_EXPORTER_OTLP_TRACES_E NDPOINT Sends traces to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316/v1/traces . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ traces, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). OTEL_TRACES_SAMPLER_ARG Sets the traces sampler endpoint. • For applications running in host mode, set this to http://localhost:2 000 . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :2000, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). Set to the installation location of ADOT .NET automatic instrumentation. OTEL_DOTNET_AUTO_HOME Enable your applications on Amazon ECS 1421 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_DOTNET_AUTO_PLUGINS Set to AWS.Distro.OpenTel emetry.AutoInstrumentation. Plugin, AWS.Distro.OpenTel emetry.AutoInstrumentation enable the Application Signals plugin. to CORECLR_ENABLE_PROFILING Set to 1 to enable the profiler. CORECLR_PROFILER Set to {918728DD-259F-4A6A-AC2B- as the CLSID of the B85E1B658318} profiler. CORECLR_PROFILER_PATH Set this to the path of the profiler. On Linux, set it to ${OTEL_DO TNET_AUTO_HOME}/linux-x64/O penTelemetry.AutoInstrument ation.Native.so On Windows Server, set it to ${OTEL_DO TNET_AUTO_HOME}/win-x64/Ope nTelemetry.AutoInstrumentat ion.Native.dll DOTNET_ADDITIONAL_DEPS Set this to the folder path of ${OTEL_DO TNET_AUTO_HOME}/AdditionalD eps . DOTNET_SHARED_STORE Set this to the folder path of ${OTEL_DO TNET_AUTO_HOME}/store . DOTNET_STARTUP_HOOKS Set this to path of the managed assembly ${OTEL_DOTNET_AUTO_HOME}/ne t/OpenTelemetry.AutoInstrum entation.StartupHook.dll before the main application's entry point. to run Enable your applications on Amazon ECS 1422 Amazon CloudWatch User Guide 5. Mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. For Linux, use the following. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "CORECLR_ENABLE_PROFILING", "value": "1" }, { "name": "CORECLR_PROFILER", "value": "{918728DD-259F-4A6A-AC2B-B85E1B658318}" }, { "name": "CORECLR_PROFILER_PATH", "value": "/otel-auto-instrumentation/linux-x64/ OpenTelemetry.AutoInstrumentation.Native.so" }, { "name": "DOTNET_ADDITIONAL_DEPS", "value": "/otel-auto-instrumentation/AdditionalDeps" }, { "name": "DOTNET_SHARED_STORE", "value": "/otel-auto-instrumentation/store" }, { "name": "DOTNET_STARTUP_HOOKS", "value": "/otel-auto-instrumentation/net/ OpenTelemetry.AutoInstrumentation.StartupHook.dll" }, { "name": "OTEL_DOTNET_AUTO_HOME", "value": "/otel-auto-instrumentation" }, { "name": "OTEL_DOTNET_AUTO_PLUGINS", Enable your applications on Amazon ECS 1423 Amazon CloudWatch User Guide "value": "AWS.Distro.OpenTelemetry.AutoInstrumentation.Plugin, AWS.Distro.OpenTelemetry.AutoInstrumentation" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", "value":
acw-ug-383
acw-ug.pdf
383
CloudWatch User Guide 5. Mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. For Linux, use the following. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "CORECLR_ENABLE_PROFILING", "value": "1" }, { "name": "CORECLR_PROFILER", "value": "{918728DD-259F-4A6A-AC2B-B85E1B658318}" }, { "name": "CORECLR_PROFILER_PATH", "value": "/otel-auto-instrumentation/linux-x64/ OpenTelemetry.AutoInstrumentation.Native.so" }, { "name": "DOTNET_ADDITIONAL_DEPS", "value": "/otel-auto-instrumentation/AdditionalDeps" }, { "name": "DOTNET_SHARED_STORE", "value": "/otel-auto-instrumentation/store" }, { "name": "DOTNET_STARTUP_HOOKS", "value": "/otel-auto-instrumentation/net/ OpenTelemetry.AutoInstrumentation.StartupHook.dll" }, { "name": "OTEL_DOTNET_AUTO_HOME", "value": "/otel-auto-instrumentation" }, { "name": "OTEL_DOTNET_AUTO_PLUGINS", Enable your applications on Amazon ECS 1423 Amazon CloudWatch User Guide "value": "AWS.Distro.OpenTelemetry.AutoInstrumentation.Plugin, AWS.Distro.OpenTelemetry.AutoInstrumentation" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "aws.log.group.names=$YOUR_APPLICATION_LOG_GROUP,service.name=dotnet-service- name" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://localhost:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/traces" }, { "name": "OTEL_EXPORTER_OTLP_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://CW_CONTAINER_IP:2000" Enable your applications on Amazon ECS 1424 Amazon CloudWatch }, { "name": "OTEL_PROPAGATORS", "value": "tracecontext,baggage,b3,xray" User Guide } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "/otel-auto-instrumentation", "readOnly": false } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] } For Windows Server, use the following. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "CORECLR_ENABLE_PROFILING", "value": "1" }, { "name": "CORECLR_PROFILER", Enable your applications on Amazon ECS 1425 Amazon CloudWatch User Guide "value": "{918728DD-259F-4A6A-AC2B-B85E1B658318}" }, { "name": "CORECLR_PROFILER_PATH", "value": "C:\\otel-auto-instrumentation\\win-x64\ \OpenTelemetry.AutoInstrumentation.Native.dll" }, { "name": "DOTNET_ADDITIONAL_DEPS", "value": "C:\\otel-auto-instrumentation\\AdditionalDeps" }, { "name": "DOTNET_SHARED_STORE", "value": "C:\\otel-auto-instrumentation\\store" }, { "name": "DOTNET_STARTUP_HOOKS", "value": "C:\\otel-auto-instrumentation\\net\ \OpenTelemetry.AutoInstrumentation.StartupHook.dll" }, { "name": "OTEL_DOTNET_AUTO_HOME", "value": "C:\\otel-auto-instrumentation" }, { "name": "OTEL_DOTNET_AUTO_PLUGINS", "value": "AWS.Distro.OpenTelemetry.AutoInstrumentation.Plugin, AWS.Distro.OpenTelemetry.AutoInstrumentation" }, { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "aws.log.group.names=$YOUR_APPLICATION_LOG_GROUP,service.name=dotnet-service- name" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { Enable your applications on Amazon ECS 1426 Amazon CloudWatch User Guide "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/traces" }, { "name": "OTEL_EXPORTER_OTLP_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://CW_CONTAINER_IP:2000" }, { "name": "OTEL_PROPAGATORS", "value": "tracecontext,baggage,b3,xray" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation", "containerPath": "C:\\otel-auto-instrumentation", "readOnly": false } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } Enable your applications on Amazon ECS 1427 Amazon CloudWatch User Guide ] } Note Node.js If you are enabling Application Signals for a Node.js application with ESM, see Setting up a Node.js application with the ESM module format before you start these steps. To instrument your application on Amazon ECS with the CloudWatch agent 1. First, specify a bind mount. The volume will be used to share files across containers in the next steps. You will use this bind mount later in this procedure. "volumes": [ { "name": "opentelemetry-auto-instrumentation-node" } ] 2. Append a new container init to your application's task definition. Replace $IMAGE with the latest image from the AWS Distro for OpenTelemetry Amazon ECR image repository. { "name": "init", "image": "$IMAGE", "essential": false, "command": [ "cp", "-a", "/autoinstrumentation/.", "/otel-auto-instrumentation-node" ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-node", "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } Enable your applications on Amazon ECS 1428 Amazon CloudWatch ], } User Guide 3. Add a dependency on the init container to make sure that this container finishes before your application container starts. "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] 4. Add the following environment variables to your application container. Environment variable Setting to enable Application Signals OTEL_RESOURCE_ATTRIBUTES Specify the following information as key- value pairs: • service.name sets the name of the service. This will be diplayed as the service name for your application in Application Signals dashboards. If you don't provide a value for this key, the default of UnknownService is used. • deployment.environment sets the environment that the application runs in. This will be diplayed as the Hosted In environment of your applicati on in Application Signals dashboards. If you don't specify this, the default of generic:default is used. This attribute key is used only by Applicati on Signals, and is converted into X-Ray trace annotations and CloudWatch metric dimensions. Enable your applications on Amazon ECS 1429 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals (Optional) To enable log correlation for Application Signals, set an additiona l environment variable aws.log.g roup.names for your application log. By doing so, the to be the log group name traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To
acw-ug-384
acw-ug.pdf
384
Guide Environment variable Setting to enable Application Signals (Optional) To enable log correlation for Application Signals, set an additiona l environment variable aws.log.g roup.names for your application log. By doing so, the to be the log group name traces and metrics from your applicati on can be correlated with the relevant log entries from the log group. For this variable, replace $YOUR_APPLICATION_ LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-gro up-1&log-group-2 to log correlation, setting this current . To enable metric environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. Set to true to have your container start sending X-Ray traces and CloudWatch metrics to Application Signals. Set to none to disable other metrics exporters. Set to none to disable other logs exporters. OTEL_AWS_APPLICATION_SIGNAL S_ENABLED OTEL_METRICS_EXPORTER OTEL_LOGS_EXPORTER Enable your applications on Amazon ECS 1430 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_EXPORTER_OTLP_PROTOCOL Set to http/protobuf to send metrics and traces to Application Signals using OTLP/HTTP and protobuf. OTEL_AWS_APPLICATION_SIGNAL S_EXPORTER_ENDPOINT Sends metrics to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316/v1/metrics . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ metrics, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). OTEL_EXPORTER_OTLP_TRACES_E NDPOINT Sends traces to the CloudWatch daemon container. • For applications running in host mode, set this to http://localhost:4 316/v1/traces . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :4316/v1/ traces, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). Enable your applications on Amazon ECS 1431 Amazon CloudWatch User Guide Environment variable Setting to enable Application Signals OTEL_TRACES_SAMPLER Set this to xray to set X-Ray as the traces sampler. OTEL_TRACES_SAMPLER_ARG Sets the traces sampler endpoint. • For applications running in host mode, set this to http://localhost:2 000 . • For applications running in bridge mode or awsvpc mode, set this to http://CW_CONTAINER_IP :2000, where CW_CONTAINER_IP is the private IP address of the EC2 container instance. You can retrieve this address from the Instance Metadata Service (IMDS). OTEL_PROPAGATORS Set xray as one of the propagators. NODE_OPTIONS Set to --require AWS_ADOT_ NODE_INSTRUMENTATION_PATH Replace AWS_ADOT_NODE_INST . RUMENTATION_PATH where the AWS Distro for OpenTelemetry with the path Node.js auto-instrumentation is stored. For example, /otel-auto-instrum entation-node/autoinstrumen tation.js 5. Mount the volume opentelemetry-auto-instrumentation-node that you defined in step 1 of this procedure. If you don't need to enable log correlation with metrics and traces, use the following example for a Node.js application. If you want to enable log correlation, see the next step instead. For your Application Container, add a dependency on the init container to make sure that container finishes before your application container starts. Enable your applications on Amazon ECS 1432 Amazon CloudWatch User Guide { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service.name=$SVC_NAME" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/traces" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://CW_CONTAINER_IP:2000" }, { "name": "NODE_OPTIONS", Enable your applications on Amazon ECS 1433 Amazon CloudWatch User Guide "value": "--require /otel-auto-instrumentation-node/ autoinstrumentation.js" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-node", "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] } 6. (Optional) To enable log correlation, do the following before you mount the volume. In OTEL_RESOURCE_ATTRIBUTES, set an additional environment variable aws.log.group.names for the log groups of your application. By doing so, the traces and metrics from your application can be correlated with the relevant log entries from these log groups. For this variable, replace $YOUR_APPLICATION_LOG_GROUP with the log group names for your application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-group-1&log- group-2. To enable metric to log correlation, setting this current environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. The following is an example. Use this example to enable log correlation when you mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. { "name": "my-app",
acw-ug-385
acw-ug.pdf
385
application. If you have multiple log groups, you can use an ampersand (&) to separate them as in this example: aws.log.group.names=log-group-1&log- group-2. To enable metric to log correlation, setting this current environmental variable is enough. For more information, see Enable metric to log correlation. To enable trace to log correlation, you'll also need to change the logging configuration in your application. For more information, see Enable trace to log correlation. The following is an example. Use this example to enable log correlation when you mount the volume opentelemetry-auto-instrumentation that you defined in step 1 of this procedure. { "name": "my-app", ... "environment": [ { "name": "OTEL_RESOURCE_ATTRIBUTES", Enable your applications on Amazon ECS 1434 Amazon CloudWatch "value": User Guide "aws.log.group.names=$YOUR_APPLICATION_LOG_GROUP,service.name=$SVC_NAME" }, { "name": "OTEL_LOGS_EXPORTER", "value": "none" }, { "name": "OTEL_METRICS_EXPORTER", "value": "none" }, { "name": "OTEL_EXPORTER_OTLP_PROTOCOL", "value": "http/protobuf" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_ENABLED", "value": "true" }, { "name": "OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/metrics" }, { "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://CW_CONTAINER_IP:4316/v1/traces" }, { "name": "OTEL_TRACES_SAMPLER", "value": "xray" }, { "name": "OTEL_TRACES_SAMPLER_ARG", "value": "endpoint=http://CW_CONTAINER_IP:2000" }, { "name": "NODE_OPTIONS", "value": "--require /otel-auto-instrumentation-node/ autoinstrumentation.js" } ], "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-node", Enable your applications on Amazon ECS 1435 Amazon CloudWatch User Guide "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } ], "dependsOn": [ { "containerName": "init", "condition": "SUCCESS" } ] } Setting up a Node.js application with the ESM module format We provide limited support for Node.js applications with the ESM module format. For details, see the section called “Known limitations about Node.js with ESM”. For the ESM module format, using the init container to inject the Node.js instrumentation SDK doesn’t apply. To enable Application Signals for Node.js with ESM, skip steps 1 and 2 in of the previous procedure, and do the following instead. To enable Application Signals for a Node.js application with ESM 1. Install the relevant dependencies to your Node.js application for autoinstrumentation: npm install @aws/aws-distro-opentelemetry-node-autoinstrumentation npm install @opentelemetry/instrumentation@0.54.0 2. In steps 4 and 5 in the previous procedure, remove the mounting of the volume opentelemetry-auto-instrumentation-node: "mountPoints": [ { "sourceVolume": "opentelemetry-auto-instrumentation-node", "containerPath": "/otel-auto-instrumentation-node", "readOnly": false } ] Enable your applications on Amazon ECS 1436 Amazon CloudWatch User Guide Replace the node options with the following. { "name": "NODE_OPTIONS", "value": "--import @aws/aws-distro-opentelemetry-node-autoinstrumentation/ register --experimental-loader=@opentelemetry/instrumentation/hook.mjs" } Step 6: Deploy your application Create a new revision of your task definition and deploy it to your application cluster. You should see two containers in the newly created task: • init– A required container for initializing Application Signals • my-app– This is the example application container in our documentation. In your actual workloads, this specific container might not exist or might be replaced with your own service containers. (Optional) Step 7: Monitor your application health Once you have enabled your applications on Amazon ECS, you can monitor your application health. For more information, see Monitor the operational health of your applications with Application Signals. Enable Application Signals on Amazon ECS using AWS CDK To enable Application Signals on Amazon ECS using AWS CDK, do the following. 1. Enable Application Signals for your applications – If you haven't enabled Application Signals in this account yet, you must grant Application Signals the permissions it needs to discover your services. import { aws_applicationsignals as applicationsignals } from 'aws-cdk-lib'; const cfnDiscovery = new applicationsignals.CfnDiscovery(this, 'ApplicationSignalsServiceRole', { } ); Enable your applications on Amazon ECS 1437 Amazon CloudWatch User Guide The Discovery CloudFormation resource grants Application Signals the following permissions: • xray:GetServiceGraph • logs:StartQuery • logs:GetQueryResults • cloudwatch:GetMetricData • cloudwatch:ListMetrics • tag:GetResources For more information about this role, see Service-linked role permissions for CloudWatch Application Signals. 2. Instrument your application with the AWS::ApplicationSignals Construct Library in the AWS CDK. The code snippets in this document are provided in TypeScript. For other language- specific alternatives, see Supported programming languages for the AWS CDK. • Enable Application Signals on Amazon ECS with sidecar mode a. b. Configure instrumentation to instrument the application with the AWS Distro for OpenTelemetry (ADOT) SDK Agent. The following is an example of instrumenting a Java application. See InstrumentationVersion for all supported language versions. Specify cloudWatchAgentSidecar to configure the CloudWatch Agent as a sidecar container. import { Construct } from 'constructs'; import * as appsignals from '@aws-cdk/aws-applicationsignals-alpha'; import * as cdk from 'aws-cdk-lib'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import * as ecs from 'aws-cdk-lib/aws-ecs'; class MyStack extends cdk.Stack { public constructor(scope?: Construct, id?: string, props: cdk.StackProps = {}) { super(); const vpc = new ec2.Vpc(this, 'TestVpc', {}); const cluster = new ecs.Cluster(this, 'TestCluster', { vpc }); const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'SampleAppTaskDefinition', { Enable your applications on Amazon ECS 1438 Amazon CloudWatch User Guide cpu: 2048, memoryLimitMiB: 4096, }); fargateTaskDefinition.addContainer('app', { image: ecs.ContainerImage.fromRegistry('test/sample-app'), }); new appsignals.ApplicationSignalsIntegration(this, 'ApplicationSignalsIntegration', { taskDefinition: fargateTaskDefinition, instrumentation: { sdkVersion: appsignals.JavaInstrumentationVersion.V2_10_0, }, serviceName: 'sample-app', cloudWatchAgentSidecar: { containerName: 'ecs-cwagent', enableLogging: true, cpu: 256, memoryLimitMiB: 512, } }); new ecs.FargateService(this, 'MySampleApp', { cluster: cluster, taskDefinition:
acw-ug-386
acw-ug.pdf
386
from 'aws-cdk-lib/aws-ec2'; import * as ecs from 'aws-cdk-lib/aws-ecs'; class MyStack extends cdk.Stack { public constructor(scope?: Construct, id?: string, props: cdk.StackProps = {}) { super(); const vpc = new ec2.Vpc(this, 'TestVpc', {}); const cluster = new ecs.Cluster(this, 'TestCluster', { vpc }); const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'SampleAppTaskDefinition', { Enable your applications on Amazon ECS 1438 Amazon CloudWatch User Guide cpu: 2048, memoryLimitMiB: 4096, }); fargateTaskDefinition.addContainer('app', { image: ecs.ContainerImage.fromRegistry('test/sample-app'), }); new appsignals.ApplicationSignalsIntegration(this, 'ApplicationSignalsIntegration', { taskDefinition: fargateTaskDefinition, instrumentation: { sdkVersion: appsignals.JavaInstrumentationVersion.V2_10_0, }, serviceName: 'sample-app', cloudWatchAgentSidecar: { containerName: 'ecs-cwagent', enableLogging: true, cpu: 256, memoryLimitMiB: 512, } }); new ecs.FargateService(this, 'MySampleApp', { cluster: cluster, taskDefinition: fargateTaskDefinition, desiredCount: 1, }); } } • Enable Application Signals on Amazon ECS with daemon mode Note The daemon deployment strategy is not supported on Amazon ECS Fargate and is only supported on Amazon ECS on Amazon EC2. a. Run CloudWatch Agent as a daemon service with HOST network mode. b. Configure instrumentation to instrument the application with the ADOT Python Agent. Enable your applications on Amazon ECS 1439 Amazon CloudWatch User Guide import { Construct } from 'constructs'; import * as appsignals from '@aws-cdk/aws-applicationsignals-alpha'; import * as cdk from 'aws-cdk-lib'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import * as ecs from 'aws-cdk-lib/aws-ecs'; class MyStack extends cdk.Stack { public constructor(scope?: Construct, id?: string, props: cdk.StackProps = {}) { super(scope, id, props); const vpc = new ec2.Vpc(this, 'TestVpc', {}); const cluster = new ecs.Cluster(this, 'TestCluster', { vpc }); // Define Task Definition for CloudWatch agent (Daemon) const cwAgentTaskDefinition = new ecs.Ec2TaskDefinition(this, 'CloudWatchAgentTaskDefinition', { networkMode: ecs.NetworkMode.HOST, }); new appsignals.CloudWatchAgentIntegration(this, 'CloudWatchAgentIntegration', { taskDefinition: cwAgentTaskDefinition, containerName: 'ecs-cwagent', enableLogging: false, cpu: 128, memoryLimitMiB: 64, portMappings: [ { containerPort: 4316, hostPort: 4316, }, { containerPort: 2000, hostPort: 2000, }, ], }); // Create the CloudWatch Agent daemon service new ecs.Ec2Service(this, 'CloudWatchAgentDaemon', { cluster, taskDefinition: cwAgentTaskDefinition, Enable your applications on Amazon ECS 1440 Amazon CloudWatch User Guide daemon: true, // Runs one container per EC2 instance }); // Define Task Definition for user application const sampleAppTaskDefinition = new ecs.Ec2TaskDefinition(this, 'SampleAppTaskDefinition', { networkMode: ecs.NetworkMode.HOST, }); sampleAppTaskDefinition.addContainer('app', { image: ecs.ContainerImage.fromRegistry('test/sample-app'), cpu: 0, memoryLimitMiB: 512, }); // No CloudWatch Agent sidecar is needed as application container communicates to CloudWatch Agent daemon through host network new appsignals.ApplicationSignalsIntegration(this, 'ApplicationSignalsIntegration', { taskDefinition: sampleAppTaskDefinition, instrumentation: { sdkVersion: appsignals.PythonInstrumentationVersion.V0_8_0 }, serviceName: 'sample-app' }); new ecs.Ec2Service(this, 'MySampleApp', { cluster, taskDefinition: sampleAppTaskDefinition, desiredCount: 1, }); } } • Enable Application Signals on Amazon ECS with replica mode Note Running CloudWatch Agent service using replica mode requires specific security group configurations to enable communication with other services. For Application Signals functionality, configure the security group with the minimum inbound Enable your applications on Amazon ECS 1441 Amazon CloudWatch User Guide rules: Port 2000 (HTTP) and Port 4316 (HTTP). This configuration ensures proper connectivity between the CloudWatch Agent and dependent services. a. Run CloudWatch Agent as a replica service with service connect. b. Configure instrumentation to instrument the application with the ADOT Python Agent. c. Override environment variables by configuring overrideEnvironments to use service connect endpoints to communicate to the CloudWatch agent server. import { Construct } from 'constructs'; import * as appsignals from '@aws-cdk/aws-applicationsignals-alpha'; import * as cdk from 'aws-cdk-lib'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import * as ecs from 'aws-cdk-lib/aws-ecs'; import { PrivateDnsNamespace } from 'aws-cdk-lib/aws-servicediscovery'; class MyStack extends cdk.Stack { public constructor(scope?: Construct, id?: string, props: cdk.StackProps = {}) { super(scope, id, props); const vpc = new ec2.Vpc(this, 'TestVpc', {}); const cluster = new ecs.Cluster(this, 'TestCluster', { vpc }); const dnsNamespace = new PrivateDnsNamespace(this, 'Namespace', { vpc, name: 'local', }); const securityGroup = new ec2.SecurityGroup(this, 'ECSSG', { vpc }); securityGroup.addIngressRule(securityGroup, ec2.Port.tcpRange(0, 65535)); // Define Task Definition for CloudWatch agent (Replica) const cwAgentTaskDefinition = new ecs.FargateTaskDefinition(this, 'CloudWatchAgentTaskDefinition', {}); new appsignals.CloudWatchAgentIntegration(this, 'CloudWatchAgentIntegration', { taskDefinition: cwAgentTaskDefinition, containerName: 'ecs-cwagent', enableLogging: false, Enable your applications on Amazon ECS 1442 Amazon CloudWatch User Guide cpu: 128, memoryLimitMiB: 64, portMappings: [ { name: 'cwagent-4316', containerPort: 4316, hostPort: 4316, }, { name: 'cwagent-2000', containerPort: 2000, hostPort: 2000, }, ], }); // Create the CloudWatch Agent replica service with service connect new ecs.FargateService(this, 'CloudWatchAgentService', { cluster: cluster, taskDefinition: cwAgentTaskDefinition, securityGroups: [securityGroup], serviceConnectConfiguration: { namespace: dnsNamespace.namespaceArn, services: [ { portMappingName: 'cwagent-4316', dnsName: 'cwagent-4316-http', port: 4316, }, { portMappingName: 'cwagent-2000', dnsName: 'cwagent-2000-http', port: 2000, }, ], }, desiredCount: 1, }); // Define Task Definition for user application const sampleAppTaskDefinition = new ecs.FargateTaskDefinition(this, 'SampleAppTaskDefinition', {}); sampleAppTaskDefinition.addContainer('app', { Enable your applications on Amazon ECS 1443 Amazon CloudWatch User Guide image: ecs.ContainerImage.fromRegistry('test/sample-app'), cpu: 0, memoryLimitMiB: 512, }); // Overwrite environment variables to connect to the CloudWatch Agent service just created new appsignals.ApplicationSignalsIntegration(this, 'ApplicationSignalsIntegration', { taskDefinition: sampleAppTaskDefinition, instrumentation: { sdkVersion: appsignals.PythonInstrumentationVersion.V0_8_0, }, serviceName: 'sample-app', overrideEnvironments: [ { name: appsignals.CommonExporting.OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT, value: 'http://cwagent-4316-http:4316/v1/metrics', }, { name: appsignals.TraceExporting.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, value: 'http://cwagent-4316-http:4316/v1/traces', }, { name: appsignals.TraceExporting.OTEL_TRACES_SAMPLER_ARG, value: 'endpoint=http://cwagent-2000-http:2000', }, ], }); // Create ECS Service with service connect configuration new ecs.FargateService(this, 'MySampleApp', { cluster: cluster,
acw-ug-387
acw-ug.pdf
387
}, desiredCount: 1, }); // Define Task Definition for user application const sampleAppTaskDefinition = new ecs.FargateTaskDefinition(this, 'SampleAppTaskDefinition', {}); sampleAppTaskDefinition.addContainer('app', { Enable your applications on Amazon ECS 1443 Amazon CloudWatch User Guide image: ecs.ContainerImage.fromRegistry('test/sample-app'), cpu: 0, memoryLimitMiB: 512, }); // Overwrite environment variables to connect to the CloudWatch Agent service just created new appsignals.ApplicationSignalsIntegration(this, 'ApplicationSignalsIntegration', { taskDefinition: sampleAppTaskDefinition, instrumentation: { sdkVersion: appsignals.PythonInstrumentationVersion.V0_8_0, }, serviceName: 'sample-app', overrideEnvironments: [ { name: appsignals.CommonExporting.OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT, value: 'http://cwagent-4316-http:4316/v1/metrics', }, { name: appsignals.TraceExporting.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, value: 'http://cwagent-4316-http:4316/v1/traces', }, { name: appsignals.TraceExporting.OTEL_TRACES_SAMPLER_ARG, value: 'endpoint=http://cwagent-2000-http:2000', }, ], }); // Create ECS Service with service connect configuration new ecs.FargateService(this, 'MySampleApp', { cluster: cluster, taskDefinition: sampleAppTaskDefinition, serviceConnectConfiguration: { namespace: dnsNamespace.namespaceArn, }, desiredCount: 1, }); } } Enable your applications on Amazon ECS 1444 Amazon CloudWatch User Guide 3. Setting up a Node.js application with the ESM module format. There is limited support for Node.js applications with the ESM module format. For more information, see Known limitations about Node.js with ESM. For the ESM module format, enabling Application Signals by using the init container to inject the Node.js instrumentation SDK doesn't apply. Skip Step 2 in this procedure, and do the following instead. • Install the relevant dependencies to your Node.js application for autoinstrumentation. npm install @aws/aws-distro-opentelemetry-node-autoinstrumentation npm install @opentelemetry/instrumentation@0.54. • Update TaskDefinition. a. Add additional configuration to your application container. b. Configure NODE_OPTIONS. c. (Optional) Add CloudWatch Agent if you choose sidecar mode. import { Construct } from 'constructs'; import * as appsignals from '@aws-cdk/aws-applicationsignals-alpha'; import * as ecs from 'aws-cdk-lib/aws-ecs'; class MyStack extends cdk.Stack { public constructor(scope?: Construct, id?: string, props: cdk.StackProps = {}) { super(scope, id, props); const fargateTaskDefinition = new ecs.FargateTaskDefinition(stack, 'TestTaskDefinition', { cpu: 256, memoryLimitMiB: 512, }); const appContainer = fargateTaskDefinition.addContainer('app', { image: ecs.ContainerImage.fromRegistry('docker/cdk-test'), }); const volumeName = 'opentelemetry-auto-instrumentation' fargateTaskDefinition.addVolume({name: volumeName}); // Inject additional configurations const injector = new appsignals.NodeInjector(volumeName, appsignals.NodeInstrumentationVersion.V0_5_0); Enable your applications on Amazon ECS 1445 Amazon CloudWatch User Guide injector.renderDefaultContainer(fargateTaskDefinition); // Configure NODE_OPTIONS appContainer.addEnvironment('NODE_OPTIONS', '--import @aws/aws- distro-opentelemetry-node-autoinstrumentation/register --experimental- loader=@opentelemetry/instrumentation/hook.mjs') // Optional: add CloudWatch agent const cwAgent = new appsignals.CloudWatchAgentIntegration(stack, 'AddCloudWatchAgent', { containerName: 'ecs-cwagent', taskDefinition: fargateTaskDefinition, memoryReservationMiB: 50, }); appContainer.addContainerDependencies({ container: cwAgent.agentContainer, condition: ecs.ContainerDependencyCondition.START, }); } 4. Deploy the updated stack – Run the cdk synth command in your application's main directory. To deploy the service in your AWS account, run the cdk deploy command in your application's main directory. If you used the sidecar strategy, you'll see one service created: • APPLICATION_SERVICE is the service of your application. It includes the three following containers: • init– A required container for initializing Application Signals. • ecs-cwagent– A container running the CloudWatch agent • my-app– This is the example application container in our documentation. In your actual workloads, this specific container might not exist or might be replaced with your own service containers. If you used the daemon strategy, you'll see two services created: • CloudWatchAgentDaemon is the CloudWatch agent daemon service. • APPLICATION_SERVICE is the service of your application. It includes the two following containers: • init– A required container for initializing Application Signals. Enable your applications on Amazon ECS 1446 Amazon CloudWatch User Guide • my-app– This is the example application container in our documentation. In your actual workloads, this specific container might not exist or might be replaced with your own service containers. If you used the replica strategy, you'll see two services created: • CloudWatchAgentService is the CloudWatch agent replica service. • APPLICATION_SERVICE is the service of your application. It includes the two following containers: • init– A required container for initializing Application Signals. • my-app– This is the example application container in our documentation. In your actual workloads, this specific container might not exist or might be replaced with your own service containers. Enable your applications on Kubernetes Enable CloudWatch Application Signals on Kubernetes by using the custom setup steps described in this section. For applications running on Kubernetes, you install and configure the CloudWatch agent and AWS Distro for OpenTelemetry yourself. On these architectures enabled with a custom Application Signals setup, Application Signals doesn't autodiscover the names of your services or the hosts or clusters they run on. You must specify these names during the custom setup, and the names that you specify are what is displayed on Application Signals dashboards. Requirements • You have admininstrator permission on the Kubernetes cluster where you are enabling Application Signals. • You must have the AWS CLI installed on the environment where your Kubernetes cluster is running. For more information about installing the AWS CLI, see Install or update the latest version of the AWS CLI. • You have kubectl and helm installed on your local terminal. For more information, see the kubectl and Helm documentation. Enable your applications on Kubernetes 1447 Amazon CloudWatch User Guide Step 1: Enable Application Signals in your account You must first enable Application Signals in your account. If you haven't,
acw-ug-388
acw-ug.pdf
388
You have admininstrator permission on the Kubernetes cluster where you are enabling Application Signals. • You must have the AWS CLI installed on the environment where your Kubernetes cluster is running. For more information about installing the AWS CLI, see Install or update the latest version of the AWS CLI. • You have kubectl and helm installed on your local terminal. For more information, see the kubectl and Helm documentation. Enable your applications on Kubernetes 1447 Amazon CloudWatch User Guide Step 1: Enable Application Signals in your account You must first enable Application Signals in your account. If you haven't, see Enable Application Signals in your account. Step 2: Install the CloudWatch agent operator in your cluster Installing the CloudWatch agent operator installs the operator, the CloudWatch agent, and other auto-instrumentation into your cluster. To do so, enter the following command. Replace $REGION with your AWS Region. Replace $YOUR_CLUSTER_NAME with the name that you want to appear for your cluster in Application Signals dashboards. helm repo add aws-observability https://aws-observability.github.io/helm-charts helm install amazon-cloudwatch-operator aws-observability/amazon-cloudwatch- observability \ --namespace amazon-cloudwatch --create-namespace \ --set region=$REGION \ --set clusterName=$YOUR_CLUSTER_NAME For more information, see amazon-cloudwatch-observability on GitHub. Step 3: Set up AWS credentials for your Kubernetes clusters Important If your Kubernetes cluster is hosted on Amazon EC2, you can skip this section and proceed to Step 4: Add annotations. If your Kubernetes cluster is hosted on-premises, you must use the instructions in this section to add AWS credentials to your Kubernetes environment. To set up permissions for an on-premises Kubernetes cluster 1. Create the IAM user to be used to provide permissions to your on-premises host: a. Open the IAM console at https://console.aws.amazon.com/iam/. b. Choose Users, Create User. c. In User details, for User name, enter a name for the new IAM user. This is the sign-in name for AWS that will be used to authenticate your host. Then choose Next Enable your applications on Kubernetes 1448 Amazon CloudWatch User Guide d. On the Set permissions page, under Permissions options, select Attach policies directly. e. From the Permissions policies list, select the CloudWatchAgentServerPolicy policy to add to your user. Then choose Next. f. On the Review and create page, ensure that you are satisfied with the user name and that the CloudWatchAgentServerPolicy policy is in the Permissions summary. g. Choose Create user 2. Create and retrieve your AWS access key and secret key: a. In the navigation pane in the IAM console, choose Users and then select the user name of the user that you created in the previous step. b. On the user's page, choose the Security credentials tab. Then, in the Access keys section, choose Create access key. c. d. e. For Create access key Step 1, choose Command Line Interface (CLI). For Create access key Step 2, optionally enter a tag and then choose Next. For Create access key Step 3, select Download .csv file to save a .csv file with your IAM user's access key and secret access key. You need this information for the next steps. f. Choose Done. 3. Configure your AWS credentials in your on-premises host by entering the following command. Replace ACCESS_KEY_ID and SECRET_ACCESS_ID with your newly generated access key and secret access key from the .csv file that you downloaded in the previous step. By default, the credential file is saved in /home/user/.aws/credentials. $ aws configure --profile AmazonCloudWatchAgent AWS Access Key ID [None]: ACCESS_KEY_ID AWS Secret Access Key [None]: SECRET_ACCESS_ID Default region name [None]: MY_REGION Default output format [None]: json 4. Edit the custom resource that the CloudWatch agent installed using the Helm chart to add the newly created AWS credentials secret. kubectl edit amazoncloudwatchagent cloudwatch-agent -n amazon-cloudwatch 5. While your file editor is open mount the AWS credentials into the CloudWatch agent container by adding the following configuration to the top of the deployment. Replace the path / home/user/.aws/credentials with the location of your local AWS credentials file. Enable your applications on Kubernetes 1449 Amazon CloudWatch User Guide apiVersion: cloudwatch.aws.amazon.com/v1alpha1 kind: AmazonCloudWatchAgent metadata: name: cloudwatch-agent namespace: amazon-cloudwatch spec: volumeMounts: - mountPath: /rootfs volumeMounts: - name: aws-credentials mountPath: /root/.aws readOnly: true volumes: - hostPath: path: /home/user/.aws/credentials name: aws-credentials --- Step 4: Add annotations Note If you are enabling Application Signals for a Node.js application with ESM, skip the steps in this section and see the section called “Setting up a Node.js application with the ESM module format” instead. The next step is to instrument your application for CloudWatch Application Signals by adding a language-specific annotation to your Kubernetes workload or namespace. This annotation auto- instruments your application to send metrics, traces, and logs to Application Signals. To add the annotations for Application Signals 1. You have two options for the annotation: • Annotate Workload auto-instruments a single workload in a cluster. • Annotate Namespace auto-instruments all workloads
acw-ug-389
acw-ug.pdf
389
enabling Application Signals for a Node.js application with ESM, skip the steps in this section and see the section called “Setting up a Node.js application with the ESM module format” instead. The next step is to instrument your application for CloudWatch Application Signals by adding a language-specific annotation to your Kubernetes workload or namespace. This annotation auto- instruments your application to send metrics, traces, and logs to Application Signals. To add the annotations for Application Signals 1. You have two options for the annotation: • Annotate Workload auto-instruments a single workload in a cluster. • Annotate Namespace auto-instruments all workloads deployed in the selected namespace. Enable your applications on Kubernetes 1450 Amazon CloudWatch User Guide Choose one of those options, and follow the appropriate steps. 2. To annotate a single workload, enter one of the following commands. Replace $WORKLOAD_TYPE and $WORKLOAD_NAME with the values for your workload. • For Java workloads: kubectl patch $WORKLOAD_TYPE $WORKLOAD_NAME -p '{"spec": {"template": {"metadata": {"annotations": {"instrumentation.opentelemetry.io/inject-java": "true"}}}}}' • For Python workloads: kubectl patch $WORKLOAD_TYPE $WORKLOAD_NAME -p '{"spec": {"template": {"metadata": {"annotations": {"instrumentation.opentelemetry.io/inject-python": "true"}}}}}' For Python applications, there are additional required configurations. For more information, see Python application doesn't start after Application Signals is enabled. • For .NET workloads: kubectl patch $WORKLOAD_TYPE $WORKLOAD_NAME -p '{"spec": {"template": {"metadata": {"annotations": {"instrumentation.opentelemetry.io/inject-dotnet": "true"}}}}}' Note To enable Application Signals for a .NET workload on Alpine Linux (linux-musl- x64) based images, add the following additional annotation. instrumentation.opentelemetry.io/otel-dotnet-auto-runtime: "linux-musl- x64" • For Node.js workloads: kubectl patch $WORKLOAD_TYPE $WORKLOAD_NAME -p '{"spec": {"template": {"metadata": {"annotations": {"instrumentation.opentelemetry.io/inject-nodejs": "true"}}}}}' Enable your applications on Kubernetes 1451 Amazon CloudWatch User Guide 3. To annotate all workloads in a namespace, enter enter one of the following commands. Replace $NAMESPACE with the name of your namespace. If the namespace includes Java, Python, and .NET workloads, add all annotations to the namespace. • For Java workloads in the namespace: kubectl annotate ns $NAMESPACE instrumentation.opentelemetry.io/inject-java=true • For Python workloads in the namespace: kubectl annotate ns $NAMESPACE instrumentation.opentelemetry.io/inject- python=true For Python applications, there are additional required configurations. For more information, see Python application doesn't start after Application Signals is enabled. • For .NET workloads in the namespace: kubectl annotate ns $NAMESPACE instrumentation.opentelemetry.io/inject- dotnet=true • For Node.js workloads in the namespace: kubectl annotate ns $NAMESPACE instrumentation.opentelemetry.io/inject- nodejs=true After adding the annotations, restart all pods in the namespace by entering the following command: kubectl rollout restart 4. When the previous steps are completed, in the CloudWatch console, choose Application Signals, Services. This opens the dashboards where you can see the data that Application Signals collects. It might take a few minutes for data to appear. For more information about the Services view, see Monitor the operational health of your applications with Application Signals. Enable your applications on Kubernetes 1452 Amazon CloudWatch User Guide Setting up a Node.js application with the ESM module format We provide limited support for Node.js applications with the ESM module format. For details, see the section called “Known limitations about Node.js with ESM”. For the ESM module format, enabling Application Signals by annotating the manifest file doesn’t work. Skip the previous procedure and do the following instead: To enable Application Signals for a Node.js application with ESM 1. Install the relevant dependencies to your Node.js application for autoinstrumentation: npm install @aws/aws-distro-opentelemetry-node-autoinstrumentation npm install @opentelemetry/instrumentation@0.54.0 2. Add the following environmental variables to the Dockerfile for your application and build the image. ... ENV OTEL_AWS_APPLICATION_SIGNALS_ENABLED=true ENV OTEL_TRACES_SAMPLER_ARG='endpoint=http://cloudwatch-agent.amazon- cloudwatch:2000' ENV OTEL_TRACES_SAMPLER='xray' ENV OTEL_EXPORTER_OTLP_PROTOCOL='http/protobuf' ENV OTEL_EXPORTER_OTLP_TRACES_ENDPOINT='http://cloudwatch-agent.amazon- cloudwatch:4316/v1/traces' ENV OTEL_AWS_APPLICATION_SIGNALS_EXPORTER_ENDPOINT='http://cloudwatch-agent.amazon- cloudwatch:4316/v1/metrics' ENV OTEL_METRICS_EXPORTER='none' ENV OTEL_LOGS_EXPORTER='none' ENV NODE_OPTIONS='--import @aws/aws-distro-opentelemetry-node-autoinstrumentation/ register --experimental-loader=@opentelemetry/instrumentation/hook.mjs' ENV OTEL_SERVICE_NAME='YOUR_SERVICE_NAME' #replace with a proper service name ENV OTEL_PROPAGATORS='tracecontext,baggage,b3,xray' ... # command to start the application # for example # CMD ["node", "index.mjs"] 3. Add the environmental variables OTEL_RESOURCE_ATTRIBUTES_POD_NAME, OTEL_RESOURCE_ATTRIBUTES_NODE_NAME, Enable your applications on Kubernetes 1453 Amazon CloudWatch User Guide OTEL_RESOURCE_ATTRIBUTES_DEPLOYMENT_NAME, POD_NAMESPACE and OTEL_RESOURCE_ATTRIBUTES to the deployment yaml file for the application. For example: apiVersion: apps/v1 kind: Deployment metadata: name: nodejs-app labels: app: nodejs-app spec: replicas: 2 selector: matchLabels: app: nodejs-app template: metadata: labels: app: nodejs-app # annotations: # make sure this annotation doesn't exit # instrumentation.opentelemetry.io/inject-nodejs: 'true' spec: containers: - name: nodejs-app image:your-nodejs-application-image #replace it with a proper image uri imagePullPolicy: Always ports: - containerPort: 8000 env: - name: OTEL_RESOURCE_ATTRIBUTES_POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: OTEL_RESOURCE_ATTRIBUTES_NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName - name: OTEL_RESOURCE_ATTRIBUTES_DEPLOYMENT_NAME valueFrom: fieldRef: fieldPath: metadata.labels['app'] # Assuming 'app' label is set to the deployment name - name: POD_NAMESPACE Enable your applications on Kubernetes 1454 Amazon CloudWatch User Guide valueFrom: fieldRef: fieldPath: metadata.namespace - name: OTEL_RESOURCE_ATTRIBUTES value: "k8s.deployment.name= $(OTEL_RESOURCE_ATTRIBUTES_DEPLOYMENT_NAME),k8s.namespace.name= $(POD_NAMESPACE),k8s.node.name=$(OTEL_RESOURCE_ATTRIBUTES_NODE_NAME),k8s.pod.name= $(OTEL_RESOURCE_ATTRIBUTES_POD_NAME)" 4. Deploy the Node.js application to the Kubernetes cluster. (Optional) Step 5: Monitor your application health Once you have enabled your applications on Kubernetes, you can monitor your application health. For more information, see Monitor the operational health of your applications with Application Signals. Enable your applications on Lambda You can enable
acw-ug-390
acw-ug.pdf
390
name: OTEL_RESOURCE_ATTRIBUTES_NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName - name: OTEL_RESOURCE_ATTRIBUTES_DEPLOYMENT_NAME valueFrom: fieldRef: fieldPath: metadata.labels['app'] # Assuming 'app' label is set to the deployment name - name: POD_NAMESPACE Enable your applications on Kubernetes 1454 Amazon CloudWatch User Guide valueFrom: fieldRef: fieldPath: metadata.namespace - name: OTEL_RESOURCE_ATTRIBUTES value: "k8s.deployment.name= $(OTEL_RESOURCE_ATTRIBUTES_DEPLOYMENT_NAME),k8s.namespace.name= $(POD_NAMESPACE),k8s.node.name=$(OTEL_RESOURCE_ATTRIBUTES_NODE_NAME),k8s.pod.name= $(OTEL_RESOURCE_ATTRIBUTES_POD_NAME)" 4. Deploy the Node.js application to the Kubernetes cluster. (Optional) Step 5: Monitor your application health Once you have enabled your applications on Kubernetes, you can monitor your application health. For more information, see Monitor the operational health of your applications with Application Signals. Enable your applications on Lambda You can enable Application Signals for your Lambda functions. Application Signals automatically instruments your Lambda functions using enhanced AWS Distro for OpenTelemetry (ADOT) libraries, provided through a Lambda layer. This AWS Lambda Layer for OpenTelemetry packages and deploys the libraries that are required for auto-instrumentation for Application Signals. In addition to supporting Application Signals, this Lambda layer is also a component of Lambda OpenTelemetry support and provides tracing functionality. Topics • Getting started • Use the CloudWatch Application Signals console • Use the Lambda console • Enable Application Signals on Lambda using AWS CDK • (Optional) Monitor your application health • Manually enable Application Signals. • Manually disable Application Signals • Configuring Application Signals • AWS Lambda Layer for OpenTelemetry ARNs • Deploy Lambda functions using Amazon ECR container Enable your applications on Lambda 1455 Amazon CloudWatch Getting started User Guide There are three methods for enabling Application Signals for your Lambda functions. After you enable Application Signals for a Lambda function, it takes a few minutes for telemetry from that function to appear in the Application Signals console. • Use the CloudWatch Application Signals console • Use the Lambda console • Manually add the AWS Lambda Layer for OpenTelemetry to your Lambda function runtime. Each of these methods adds the AWS Lambda Layer for OpenTelemetry to your function. Use the CloudWatch Application Signals console Use these steps to use the Application Signals console to enable Application Signals for a Lambda function. 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. 3. In the navigation pane, choose Application Signals, Services. In the Services list area, choose Enable Application Signals. 4. Choose the Lambda tile. 5. Select each function that you want to enable for Application Signals, and then choose Done. Use the Lambda console Use these steps to use the Lambda console to enable Application Signals for a Lambda function. 1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 2. In the navigation pane, choose Functions and then choose the name of the function that you want to enable. 3. Choose the Configuration tab, and then choose Monitoring and operations tools. 4. Choose Edit. 5. In the CloudWatch Application Signals and X-Ray section, select both Automatically collect application traces and standard application metrics with Application Signals and Automatically collect Lambda service traces for end to end visibility with X-Ray.. Enable your applications on Lambda 1456 Amazon CloudWatch 6. Choose Save. User Guide Enable Application Signals on Lambda using AWS CDK If you haven't enabled Application Signals in this account yet, you must grant Application Signals the permissions it needs to discover your services. For more information, see Enable Application Signals in your account. 1. Enable Application Signals for your applications import { aws_applicationsignals as applicationsignals } from 'aws-cdk-lib'; const cfnDiscovery = new applicationsignals.CfnDiscovery(this, 'ApplicationSignalsServiceRole', { } ); The Discovery CloudFormation resource grants Application Signals the following permissions: • xray:GetServiceGraph • logs:StartQuery • logs:GetQueryResults • cloudwatch:GetMetricData • cloudwatch:ListMetrics • tag:GetResources For more information about this role, see Service-linked role permissions for CloudWatch Application Signals. 2. Add the IAM policy CloudWatchLambdaApplicationSignalsExecutionRolePolicy to the lambda function. const fn = new Function(this, 'DemoFunction', { code: Code.fromAsset('$YOUR_LAMBDA.zip'), runtime: Runtime.PYTHON_3_12, handler: '$YOUR_HANDLER' }) fn.role?.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName('CloudWatchLambdaApplicationSignalsExecutionRolePolicy')); Enable your applications on Lambda 1457 Amazon CloudWatch User Guide 3. Replace $AWS_LAMBDA_LAYER_FOR_OTEL_ARN with the actual AWS Lambda Layer for OpenTelemetry ARN in the corresponding region. fn.addLayers(LayerVersion.fromLayerVersionArn( this, 'AwsLambdaLayerForOtel', '$AWS_LAMBDA_LAYER_FOR_OTEL_ARN' )) fn.addEnvironment("AWS_LAMBDA_EXEC_WRAPPER", "/opt/otel-instrument"); (Optional) Monitor your application health Once you have enabled your applications on Lambda, you can monitor your application health. For more information, see Monitor the operational health of your applications with Application Signals. Manually enable Application Signals. Use these steps to manually enable Application Signals for a Lambda function. 1. Add the AWS Lambda Layer for OpenTelemetry to your Lambda runtime. To find the layer ARN, see AWS Lambda Layer for OpenTelemetry ARNs. 2. Add the environment variable AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-instrument Add the environment variable LAMBDA_APPLICATION_SIGNALS_REMOTE_ENVIRONMENT to configure custom Lambda environments. By default, lambda environments are configured to lambda:default. 3. Attach the AWS managed IAM policy CloudWatchLambdaApplicationSignalsExecutionRolePolicy to the Lambda execution role. 4. (Optional) We recommend that you enable Lambda active tracing to get a better tracing experience. For more information, see Visualize Lambda function invocations using AWS X- Ray. Manually disable Application Signals To manually
acw-ug-391
acw-ug.pdf
391
Signals for a Lambda function. 1. Add the AWS Lambda Layer for OpenTelemetry to your Lambda runtime. To find the layer ARN, see AWS Lambda Layer for OpenTelemetry ARNs. 2. Add the environment variable AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-instrument Add the environment variable LAMBDA_APPLICATION_SIGNALS_REMOTE_ENVIRONMENT to configure custom Lambda environments. By default, lambda environments are configured to lambda:default. 3. Attach the AWS managed IAM policy CloudWatchLambdaApplicationSignalsExecutionRolePolicy to the Lambda execution role. 4. (Optional) We recommend that you enable Lambda active tracing to get a better tracing experience. For more information, see Visualize Lambda function invocations using AWS X- Ray. Manually disable Application Signals To manually disable Application Signals for a Lambda function, remove the AWS Lambda Layer for OpenTelemetry from your Lambda runtime, and remove the AWS_LAMBDA_EXEC_WRAPPER=/opt/ otel-instrument environment variable. Enable your applications on Lambda 1458 Amazon CloudWatch User Guide Configuring Application Signals You can use this section to configure Application Signals in Lambda. Grouping multiple Lambda functions into one service Environment variable OTEL_SERVICE_NAME sets the name of the service. This will be displayed as the service name for your application in Application Signals dashboards. You can assign the same service name to multiple Lambda functions, and they will be merged into a single service in Application Signals. When you don't provide a value for this key, the default Lambda Function name is used. Sampling By default, the trace sampling strategy is parent based. You can adjust the sampling strategy by setting environment variables OTEL_TRACES_SAMPLER. For example, set trace sampling rate to 30%. OTEL_TRACES_SAMPLER=traceidratio OTEL_TRACES_SAMPLER_ARG=0.3 For more information , see OpenTelemetry Environment Variable Specification. Enabling all library instrumentation’s To reduce Lambda cold starts, by default, only AWS SDK and HTTP instrumentation’s are enabled for Python, Node, and Java. You can set environment variables to enable instrumentation for other libraries used in your Lambda function. • Python – OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=none • Node – OTEL_NODE_DISABLED_INSTRUMENTATIONS=none • Java – OTEL_INSTRUMENTATION_COMMON_DEFAULT_ENABLED=true AWS Lambda Layer for OpenTelemetry ARNs The following tables list the ARNs to use the AWS Lambda Layer for OpenTelemetry for each Region where it's supported. Enable your applications on Lambda 1459 Amazon CloudWatch Python Region ARN User Guide US East (N. Virginia) arn:aws:lambda:us-east-1:615299751070:layer:A WSOpenTelemetryDistroPython:12 US East (Ohio) arn:aws:lambda:us-east-2:615299751070:layer:A WSOpenTelemetryDistroPython:9 US West (N. Californi a) arn:aws:lambda:us-west-1:615299751070:layer:A WSOpenTelemetryDistroPython:16 US West (Oregon) arn:aws:lambda:us-west-2:615299751070:layer:A WSOpenTelemetryDistroPython:16 Africa (Cape Town) arn:aws:lambda:af-south-1:904233096616:layer: AWSOpenTelemetryDistroPython:6 Asia Pacific (Hong Kong) Asia Pacific (Hyderabad) arn:aws:lambda:ap-east-1:888577020596:layer:A WSOpenTelemetryDistroPython:6 arn:aws:lambda:ap-south-2:796973505492:layer: AWSOpenTelemetryDistroPython:6 Asia Pacific (Jakarta) arn:aws:lambda:ap-southeast-3:039612877180:la yer:AWSOpenTelemetryDistroPython:6 Asia Pacific (Melbourne) Asia Pacific (Mumbai) arn:aws:lambda:ap-southeast-4:713881805771:la yer:AWSOpenTelemetryDistroPython:6 arn:aws:lambda:ap-south-1:615299751070:layer: AWSOpenTelemetryDistroPython:9 Asia Pacific (Osaka) arn:aws:lambda:ap-northeast-3:615299751070:la yer:AWSOpenTelemetryDistroPython:8 Asia Pacific (Seoul) arn:aws:lambda:ap-northeast-2:615299751070:la yer:AWSOpenTelemetryDistroPython:9 Enable your applications on Lambda 1460 Amazon CloudWatch User Guide Region ARN Asia Pacific (Singapore) arn:aws:lambda:ap-southeast-1:615299751070:la yer:AWSOpenTelemetryDistroPython:8 Asia Pacific (Sydney) arn:aws:lambda:ap-southeast-2:615299751070:la yer:AWSOpenTelemetryDistroPython:9 Asia Pacific (Tokyo) arn:aws:lambda:ap-northeast-1:615299751070:la yer:AWSOpenTelemetryDistroPython:9 Canada (Central) arn:aws:lambda:ca-central-1:615299751070:laye r:AWSOpenTelemetryDistroPython:9 Europe (Frankfurt) arn:aws:lambda:eu-central-1:615299751070:laye r:AWSOpenTelemetryDistroPython:9 Europe (Ireland) arn:aws:lambda:eu-west-1:615299751070:layer:A WSOpenTelemetryDistroPython:9 Europe (London) arn:aws:lambda:eu-west-2:615299751070:layer:A WSOpenTelemetryDistroPython:9 Europe (Milan) arn:aws:lambda:eu-south-1:257394471194:layer: AWSOpenTelemetryDistroPython:6 Europe (Paris) arn:aws:lambda:eu-west-3:615299751070:layer:A WSOpenTelemetryDistroPython:9 Europe (Spain) arn:aws:lambda:eu-south-2:490004653786:layer: AWSOpenTelemetryDistroPython:6 Europe (Stockholm) arn:aws:lambda:eu-north-1:615299751070:layer: AWSOpenTelemetryDistroPython:9 Europe (Zurich) arn:aws:lambda:eu-central-2:156041407956:laye r:AWSOpenTelemetryDistroPython:6 Enable your applications on Lambda 1461 Amazon CloudWatch User Guide Region ARN Israel (Tel Aviv) arn:aws:lambda:il-central-1:746669239226:laye r:AWSOpenTelemetryDistroPython:6 Middle East (Bahrain) arn:aws:lambda:me-south-1:980921751758:layer: AWSOpenTelemetryDistroPython:6 Middle East (UAE) arn:aws:lambda:me-central-1:739275441131:laye r:AWSOpenTelemetryDistroPython:6 South America (São Paulo) arn:aws:lambda:sa-east-1:615299751070:layer:A WSOpenTelemetryDistroPython:9 Node.js Region ARN US East (N. Virginia) arn:aws:lambda:us-east-1:615299751070:layer:A WSOpenTelemetryDistroJs:6 US East (Ohio) arn:aws:lambda:us-east-2:615299751070:layer:A WSOpenTelemetryDistroJs:6 US West (N. Californi a) arn:aws:lambda:us-west-1:615299751070:layer:A WSOpenTelemetryDistroJs:6 US West (Oregon) arn:aws:lambda:us-west-2:615299751070:layer:A WSOpenTelemetryDistroJs:6 Africa (Cape Town) arn:aws:lambda:af-south-1:904233096616:layer: AWSOpenTelemetryDistroJs:6 Asia Pacific (Hong Kong) Asia Pacific (Hyderabad) arn:aws:lambda:ap-east-1:888577020596:layer:A WSOpenTelemetryDistroJs:6 arn:aws:lambda:ap-south-2:796973505492:layer: AWSOpenTelemetryDistroJs:6 Enable your applications on Lambda 1462 Amazon CloudWatch User Guide Region ARN Asia Pacific (Jakarta) arn:aws:lambda:ap-southeast-3:039612877180:la yer:AWSOpenTelemetryDistroJs:6 Asia Pacific (Melbourne) Asia Pacific (Mumbai) arn:aws:lambda:ap-southeast-4:713881805771:la yer:AWSOpenTelemetryDistroJs:6 arn:aws:lambda:ap-south-1:615299751070:layer: AWSOpenTelemetryDistroJs:6 Asia Pacific (Osaka) arn:aws:lambda:ap-northeast-3:615299751070:la yer:AWSOpenTelemetryDistroJs:6 Asia Pacific (Seoul) arn:aws:lambda:ap-northeast-2:615299751070:la yer:AWSOpenTelemetryDistroJs:6 Asia Pacific (Singapore) arn:aws:lambda:ap-southeast-1:615299751070:la yer:AWSOpenTelemetryDistroJs:6 Asia Pacific (Sydney) arn:aws:lambda:ap-southeast-2:615299751070:la yer:AWSOpenTelemetryDistroJs:6 Asia Pacific (Tokyo) arn:aws:lambda:ap-northeast-1:615299751070:la yer:AWSOpenTelemetryDistroJs:6 Canada (Central) arn:aws:lambda:ca-central-1:615299751070:laye r:AWSOpenTelemetryDistroJs:6 Europe (Frankfurt) arn:aws:lambda:eu-central-1:615299751070:laye r:AWSOpenTelemetryDistroJs:6 Europe (Ireland) arn:aws:lambda:eu-west-1:615299751070:layer:A WSOpenTelemetryDistroJs:6 Europe (London) arn:aws:lambda:eu-west-2:615299751070:layer:A WSOpenTelemetryDistroJs:6 Enable your applications on Lambda 1463 Amazon CloudWatch User Guide Region ARN Europe (Milan) arn:aws:lambda:eu-south-1:257394471194:layer: AWSOpenTelemetryDistroJs:6 Europe (Paris) arn:aws:lambda:eu-west-3:615299751070:layer:A WSOpenTelemetryDistroJs:6 Europe (Spain) arn:aws:lambda:eu-south-2:490004653786:layer: AWSOpenTelemetryDistroJs:6 Europe (Stockholm) arn:aws:lambda:eu-north-1:615299751070:layer: AWSOpenTelemetryDistroJs:6 Europe (Zurich) arn:aws:lambda:eu-central-2:156041407956:laye r:AWSOpenTelemetryDistroJs:6 Israel (Tel Aviv) arn:aws:lambda:il-central-1:746669239226:laye r:AWSOpenTelemetryDistroJs:6 Middle East (Bahrain) arn:aws:lambda:me-south-1:980921751758:layer: AWSOpenTelemetryDistroJs:6 Middle East (UAE) arn:aws:lambda:me-central-1:739275441131:laye r:AWSOpenTelemetryDistroJs:6 South America (São Paulo) arn:aws:lambda:sa-east-1:615299751070:layer:A WSOpenTelemetryDistroJs:6 .Net Region ARN US East (N. Virginia) arn:aws:lambda:us-east-1:615299751070:layer:A WSOpenTelemetryDistroDotNet:4 US East (Ohio) arn:aws:lambda:us-east-2:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Enable your applications on Lambda 1464 Amazon CloudWatch User Guide Region ARN US West (N. Californi a) arn:aws:lambda:us-west-1:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 US West (Oregon) arn:aws:lambda:us-west-2:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Africa (Cape Town) arn:aws:lambda:af-south-1:904233096616:layer: AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Hong Kong) Asia Pacific (Hyderabad) arn:aws:lambda:ap-east-1:888577020596:layer:A WSOpenTelemetryDistroDotNet:3 arn:aws:lambda:ap-south-2:796973505492:layer: AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Jakarta) arn:aws:lambda:ap-southeast-3:039612877180:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Melbourne) Asia Pacific (Mumbai) arn:aws:lambda:ap-southeast-4:713881805771:la yer:AWSOpenTelemetryDistroDotNet:3 arn:aws:lambda:ap-south-1:615299751070:layer: AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Osaka) arn:aws:lambda:ap-northeast-3:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Seoul) arn:aws:lambda:ap-northeast-2:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Singapore) arn:aws:lambda:ap-southeast-1:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Sydney) arn:aws:lambda:ap-southeast-2:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Enable your applications on Lambda 1465 Amazon CloudWatch User Guide Region ARN Asia Pacific (Tokyo) arn:aws:lambda:ap-northeast-1:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Canada (Central) arn:aws:lambda:ca-central-1:615299751070:laye r:AWSOpenTelemetryDistroDotNet:3 Europe (Frankfurt) arn:aws:lambda:eu-central-1:615299751070:laye r:AWSOpenTelemetryDistroDotNet:3 Europe (Ireland) arn:aws:lambda:eu-west-1:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Europe (London) arn:aws:lambda:eu-west-2:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Europe (Milan) arn:aws:lambda:eu-south-1:257394471194:layer: AWSOpenTelemetryDistroDotNet:3 Europe
acw-ug-392
acw-ug.pdf
392
West (N. Californi a) arn:aws:lambda:us-west-1:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 US West (Oregon) arn:aws:lambda:us-west-2:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Africa (Cape Town) arn:aws:lambda:af-south-1:904233096616:layer: AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Hong Kong) Asia Pacific (Hyderabad) arn:aws:lambda:ap-east-1:888577020596:layer:A WSOpenTelemetryDistroDotNet:3 arn:aws:lambda:ap-south-2:796973505492:layer: AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Jakarta) arn:aws:lambda:ap-southeast-3:039612877180:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Melbourne) Asia Pacific (Mumbai) arn:aws:lambda:ap-southeast-4:713881805771:la yer:AWSOpenTelemetryDistroDotNet:3 arn:aws:lambda:ap-south-1:615299751070:layer: AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Osaka) arn:aws:lambda:ap-northeast-3:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Seoul) arn:aws:lambda:ap-northeast-2:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Singapore) arn:aws:lambda:ap-southeast-1:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Asia Pacific (Sydney) arn:aws:lambda:ap-southeast-2:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Enable your applications on Lambda 1465 Amazon CloudWatch User Guide Region ARN Asia Pacific (Tokyo) arn:aws:lambda:ap-northeast-1:615299751070:la yer:AWSOpenTelemetryDistroDotNet:3 Canada (Central) arn:aws:lambda:ca-central-1:615299751070:laye r:AWSOpenTelemetryDistroDotNet:3 Europe (Frankfurt) arn:aws:lambda:eu-central-1:615299751070:laye r:AWSOpenTelemetryDistroDotNet:3 Europe (Ireland) arn:aws:lambda:eu-west-1:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Europe (London) arn:aws:lambda:eu-west-2:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Europe (Milan) arn:aws:lambda:eu-south-1:257394471194:layer: AWSOpenTelemetryDistroDotNet:3 Europe (Paris) arn:aws:lambda:eu-west-3:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Europe (Spain) arn:aws:lambda:eu-south-2:490004653786:layer: AWSOpenTelemetryDistroDotNet:3 Europe (Stockholm) arn:aws:lambda:eu-north-1:615299751070:layer: AWSOpenTelemetryDistroDotNet:3 Europe (Zurich) arn:aws:lambda:eu-central-2:156041407956:laye r:AWSOpenTelemetryDistroDotNet:3 Israel (Tel Aviv) arn:aws:lambda:il-central-1:746669239226:laye r:AWSOpenTelemetryDistroDotNet:3 Middle East (Bahrain) arn:aws:lambda:me-south-1:980921751758:layer: AWSOpenTelemetryDistroDotNet:3 Enable your applications on Lambda 1466 Amazon CloudWatch User Guide Region ARN Middle East (UAE) arn:aws:lambda:me-central-1:739275441131:laye r:AWSOpenTelemetryDistroDotNet:3 South America (São Paulo) arn:aws:lambda:sa-east-1:615299751070:layer:A WSOpenTelemetryDistroDotNet:3 Java Region ARN US East (N. Virginia) arn:aws:lambda:us-east-1:615299751070:layer:A WSOpenTelemetryDistroJava:3 US East (Ohio) arn:aws:lambda:us-east-2:615299751070:layer:A WSOpenTelemetryDistroJava:3 US West (N. Californi a) arn:aws:lambda:us-west-1:615299751070:layer:A WSOpenTelemetryDistroJava:3 US West (Oregon) arn:aws:lambda:us-west-2:615299751070:layer:A WSOpenTelemetryDistroJava:3 Africa (Cape Town) arn:aws:lambda:af-south-1:904233096616:layer: AWSOpenTelemetryDistroJava:3 Asia Pacific (Hong Kong) Asia Pacific (Hyderabad) arn:aws:lambda:ap-east-1:888577020596:layer:A WSOpenTelemetryDistroJava:3 arn:aws:lambda:ap-south-2:796973505492:layer: AWSOpenTelemetryDistroJava:3 Asia Pacific (Jakarta) arn:aws:lambda:ap-southeast-3:039612877180:la yer:AWSOpenTelemetryDistroJava:3 Asia Pacific (Melbourne) arn:aws:lambda:ap-southeast-4:713881805771:la yer:AWSOpenTelemetryDistroJava:3 Enable your applications on Lambda 1467 Amazon CloudWatch User Guide Region ARN Asia Pacific (Mumbai) arn:aws:lambda:ap-south-1:615299751070:layer: AWSOpenTelemetryDistroJava:3 Asia Pacific (Osaka) arn:aws:lambda:ap-northeast-3:615299751070:la yer:AWSOpenTelemetryDistroJava:3 Asia Pacific (Seoul) arn:aws:lambda:ap-northeast-2:615299751070:la yer:AWSOpenTelemetryDistroJava:3 Asia Pacific (Singapore) arn:aws:lambda:ap-southeast-1:615299751070:la yer:AWSOpenTelemetryDistroJava:3 Asia Pacific (Sydney) arn:aws:lambda:ap-southeast-2:615299751070:la yer:AWSOpenTelemetryDistroJava:3 Asia Pacific (Tokyo) arn:aws:lambda:ap-northeast-1:615299751070:la yer:AWSOpenTelemetryDistroJava:3 Canada (Central) arn:aws:lambda:ca-central-1:615299751070:laye r:AWSOpenTelemetryDistroJava:3 Europe (Frankfurt) arn:aws:lambda:eu-central-1:615299751070:laye r:AWSOpenTelemetryDistroJava:3 Europe (Ireland) arn:aws:lambda:eu-west-1:615299751070:layer:A WSOpenTelemetryDistroJava:3 Europe (London) arn:aws:lambda:eu-west-2:615299751070:layer:A WSOpenTelemetryDistroJava:3 Europe (Milan) arn:aws:lambda:eu-south-1:257394471194:layer: AWSOpenTelemetryDistroJava:3 Europe (Paris) arn:aws:lambda:eu-west-3:615299751070:layer:A WSOpenTelemetryDistroJava:3 Enable your applications on Lambda 1468 Amazon CloudWatch User Guide Region ARN Europe (Spain) arn:aws:lambda:eu-south-2:490004653786:layer: AWSOpenTelemetryDistroJava:3 Europe (Stockholm) arn:aws:lambda:eu-north-1:615299751070:layer: AWSOpenTelemetryDistroJava:3 Europe (Zurich) arn:aws:lambda:eu-central-2:156041407956:laye r:AWSOpenTelemetryDistroJava:3 Israel (Tel Aviv) arn:aws:lambda:il-central-1:746669239226:laye r:AWSOpenTelemetryDistroJava:3 Middle East (Bahrain) arn:aws:lambda:me-south-1:980921751758:layer: AWSOpenTelemetryDistroJava:3 Middle East (UAE) arn:aws:lambda:me-central-1:739275441131:laye r:AWSOpenTelemetryDistroJava:3 South America (São Paulo) arn:aws:lambda:sa-east-1:615299751070:layer:A WSOpenTelemetryDistroJava:3 Deploy Lambda functions using Amazon ECR container Lambda functions deployed as container images do not support Lambda Layers in the traditional way. When using container images, you cannot attach a layer as you would with other Lambda deployment methods. Instead, you must manually incorporate the layer’s contents into your container image during the build process. Java You can learn how to integrate the AWS Lambda Layer for OpenTelemetry into your containerized Java Lambda function, download the layer.zip artifact, and integrate it into your Java Lambda function container to enable Application Signals monitoring. Prerequisites • AWS CLI configured with your credentials Enable your applications on Lambda 1469 Amazon CloudWatch • Docker installed User Guide • These instructions assume you are on x86_64 platform 1. Set Up Project Structure Create a directory for your Lambda function mkdir java-appsignals-container-lambda && \ cd java-appsignals-container-lambda Create a Maven project structure mkdir -p src/main/java/com/example/java/lambda mkdir -p src/main/resources 2. Create Dockerfile Download and integrate the OpenTelemetry Layer with Application Signals support directly into your Lambda container image. To do this, the Dockerfile file is created. FROM public.ecr.aws/lambda/java:21 # Install utilities RUN dnf install -y unzip wget maven # Download the OpenTelemetry Layer with AppSignals Support RUN wget https://github.com/aws-observability/aws-otel-java-instrumentation/ releases/latest/download/layer.zip -O /tmp/layer.zip # Extract and include Lambda layer contents RUN mkdir -p /opt && \ unzip /tmp/layer.zip -d /opt/ && \ chmod -R 755 /opt/ && \ rm /tmp/layer.zip # Copy and build function code COPY pom.xml ${LAMBDA_TASK_ROOT} COPY src ${LAMBDA_TASK_ROOT}/src RUN mvn clean package -DskipTests # Copy the JAR file to the Lambda runtime directory (from inside the container) Enable your applications on Lambda 1470 Amazon CloudWatch User Guide RUN mkdir -p ${LAMBDA_TASK_ROOT}/lib/ RUN cp ${LAMBDA_TASK_ROOT}/target/function.jar ${LAMBDA_TASK_ROOT}/lib/ # Set the handler CMD ["com.example.java.lambda.App::handleRequest"] Note The layer.zip file contains the OpenTelemetry instrumentation necessary for AWS Application Signals support to monitor your Lambda function. The layer extraction steps ensures: • The layer.zip contents are properly extracted to the /opt/ directory • The otel-instrument script receives proper execution permissions • The temporary layer.zip file is removed to keep the image size smaller 3. Lambda function code – Create a Java file for your Lambda handler at src/main/java/ com/example/lambda/App.java: Your project should look something like: . ### Dockerfile ### pom.xml ### src ### main ### java # ### com # ### example # ### java # ### lambda # ### App.java ### resources 4. Build and deploy the container image Set up environment variables AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) Enable your applications on Lambda 1471 Amazon CloudWatch User Guide # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region) Authenticate with ECR First with public ECR (for base image): aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws Then with your private ECR: aws ecr get-login-password --region $AWS_REGION | docker login --username AWS -- password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com Build, tag and
acw-ug-393
acw-ug.pdf
393
App.java ### resources 4. Build and deploy the container image Set up environment variables AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) Enable your applications on Lambda 1471 Amazon CloudWatch User Guide # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region) Authenticate with ECR First with public ECR (for base image): aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws Then with your private ECR: aws ecr get-login-password --region $AWS_REGION | docker login --username AWS -- password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com Build, tag and push your image # Build the Docker image docker build -t lambda-appsignals-demo . # Tag the image docker tag lambda-appsignals-demo:latest $AWS_ACCOUNT_ID.dkr.ecr. $AWS_REGION.amazonaws.com/lambda-appsignals-demo:latest # Push the image docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/lambda-appsignals- demo:latest 5. Create and configure the Lambda function Create a new function using the Lambda console. Select Container image as the deployment option. Choose Browse images to select your Amazon ECR image. 6. Testing and verifications – Test your Lambda with a simple event. If the layer integration is successful, your Lambda appears under the Application Signals service map. You will see traces and metrics for your Lambda function in the CloudWatch console. Enable your applications on Lambda 1472 Amazon CloudWatch Troubleshooting User Guide If Application Signals is not working, check the following: • Check the function logs for any errors related to the OpenTelemetry instrumentation • Verify if the environment variable AWS_LAMBDA_EXEC_WRAPPER is set correctly • Make sure the layer extraction in the Docker file completed successfully • Confirm if the IAM permissions are properly attached • If needed, increase the Timeout and Memory settings in the general configuration of the Lambda function .Net You can learn how to integrate the OpenTelemetry Layer with Application Signals support into your containerized .Net Lambda function, download the layer.zip artifact, and integrate it into your .Net Lambda function to enable Application Signals monitoring. Prerequisites • AWS CLI configured with your credentials • Docker installed • .Net 8 SDK • These instructions assume you are on x86_64 platform 1. Set Up Project Structure Create a directory for your Lambda function container image mkdir dotnet-appsignals-container-lambda && \ cd dotnet-appsignals-container-lambda 2. Create Dockerfile Download and integrate the OpenTelemetry Layer with Application Signals support directly into your Lambda container image. To do this, the Dockerfile file is created. FROM public.ecr.aws/lambda/dotnet:8 Enable your applications on Lambda 1473 Amazon CloudWatch # Install utilities RUN dnf install -y unzip wget dotnet-sdk-8.0 which # Add dotnet command to docker container's PATH ENV PATH="/usr/lib64/dotnet:${PATH}" User Guide # Download the OpenTelemetry Layer with AppSignals Support RUN wget https://github.com/aws-observability/aws-otel-dotnet-instrumentation/ releases/latest/download/layer.zip -O /tmp/layer.zip # Extract and include Lambda layer contents RUN mkdir -p /opt && \ unzip /tmp/layer.zip -d /opt/ && \ chmod -R 755 /opt/ && \ rm /tmp/layer.zip WORKDIR ${LAMBDA_TASK_ROOT} # Copy the project files COPY dotnet-lambda-function/src/dotnet-lambda-function/*.csproj ${LAMBDA_TASK_ROOT}/ COPY dotnet-lambda-function/src/dotnet-lambda-function/Function.cs ${LAMBDA_TASK_ROOT}/ COPY dotnet-lambda-function/src/dotnet-lambda-function/aws-lambda-tools- defaults.json ${LAMBDA_TASK_ROOT}/ # Install dependencies and build the application RUN dotnet restore # Use specific runtime identifier and disable ReadyToRun optimization RUN dotnet publish -c Release -o out --self-contained false / p:PublishReadyToRun=false # Copy the published files to the Lambda runtime directory RUN cp -r out/* ${LAMBDA_TASK_ROOT}/ CMD ["dotnet-lambda-function::dotnet_lambda_function.Function::FunctionHandler"] Note The layer.zip file contains the OpenTelemetry instrumentation necessary for AWS Application Signals support to monitor your Lambda function. The layer extraction steps ensures: Enable your applications on Lambda 1474 Amazon CloudWatch User Guide • The layer.zip contents are properly extracted to the /opt/ directory • The otel-instrument script receives proper execution permissions • The temporary layer.zip file is removed to keep the image size smaller 3. Lambda function code – Initialize your Lambda project using the AWS Lambda .NET template: # Install the Lambda templates if you haven't already dotnet new -i Amazon.Lambda.Templates # Create a new Lambda project dotnet new lambda.EmptyFunction -n dotnet-lambda-function Your project should look something like: . ### Dockerfile ### dotnet-lambda-function ### src # ### dotnet-lambda-function # ### Function.cs # ### Readme.md # ### aws-lambda-tools-defaults.json # ### dotnet-lambda-function.csproj ### test ### dotnet-lambda-function.Tests ### FunctionTest.cs ### dotnet-lambda-function.Tests.csproj 4. Build and deploy the container image Set up environment variables AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region) Enable your applications on Lambda 1475 Amazon CloudWatch User Guide Update the Function.cs code to: Update the dotnet-lambda-function.csproj code to: <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0>/TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <AWSProjectType>Lambda</AWSProjectType> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <PublishReadyToRun>true</PublishReadyToRun> </PropertyGroup> <ItemGroup> <PackageReference Include="Amazon.Lambda.Core" Version="2.5.0" /> <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.4" /> <PackageReference Include="AWSSDK.S3" Version="3.7.305.23" /> </ItemGroup> </Project> 5. Build and deploy the container image Set up environment variables AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION
acw-ug-394
acw-ug.pdf
394
(aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region) Enable your applications on Lambda 1475 Amazon CloudWatch User Guide Update the Function.cs code to: Update the dotnet-lambda-function.csproj code to: <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0>/TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <AWSProjectType>Lambda</AWSProjectType> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <PublishReadyToRun>true</PublishReadyToRun> </PropertyGroup> <ItemGroup> <PackageReference Include="Amazon.Lambda.Core" Version="2.5.0" /> <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.4" /> <PackageReference Include="AWSSDK.S3" Version="3.7.305.23" /> </ItemGroup> </Project> 5. Build and deploy the container image Set up environment variables AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region) Authenticate with public Amazon ECR aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws Enable your applications on Lambda 1476 Amazon CloudWatch User Guide Authenticate with private Amazon ECR aws ecr get-login-password --region $AWS_REGION | docker login --username AWS -- password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com Create Amazon ECR repository (if needed) aws ecr create-repository \ --repository-name lambda-appsignals-demo \ --region $AWS_REGION Build, tag, and push your image # Build the Docker image docker build -t lambda-appsignals-demo . # Tag the image docker tag lambda-appsignals-demo:latest $AWS_ACCOUNT_ID.dkr.ecr. $AWS_REGION.amazonaws.com/lambda-appsignals-demo:latest # Push the image docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/lambda-appsignals- demo:latest 5. Create and Configure the Lambda Function 6. Create and configure the Lambda function Create a new function using the Lambda console. Select Container image as the deployment option. Choose Browse images to select your Amazon ECR image. 7. Testing and verifications – Test your Lambda with a simple event. If the layer integration is successful, your Lambda appears under the Application Signals service map. You will see traces and metrics for your Lambda function in the CloudWatch console. Troubleshooting Enable your applications on Lambda 1477 Amazon CloudWatch User Guide If Application Signals is not working, check the following: • Check the function logs for any errors related to the OpenTelemetry instrumentation • Verify if the environment variable AWS_LAMBDA_EXEC_WRAPPER is set correctly • Make sure the layer extraction in the Docker file completed successfully • Confirm if the IAM permissions are properly attached • If needed, increase the Timeout and Memory settings in the general configuration of the Lambda function Node.js You can learn how to integrate the OpenTelemetry Layer with Application Signals support into your containerized Node.js Lambda function, download the layer.zip artifact, and integrate it into your Node.js Lambda function to enable Application Signals monitoring. Prerequisites • AWS CLI configured with your credentials • Docker installed • These instructions assume you are on x86_64 platform 1. Set Up Project Structure Create a directory for your Lambda function container image mkdir nodejs-appsignals-container-lambda &&\ cd nodejs-appsignals-container-lambda 2. Create Dockerfile Download and integrate the OpenTelemetry Layer with Application Signals support directly into your Lambda container image. To do this, the Dockerfile file is created. # Dockerfile FROM public.ecr.aws/lambda/nodejs:22 # Install utilities RUN dnf install -y unzip wget Enable your applications on Lambda 1478 Amazon CloudWatch User Guide # Download the OpenTelemetry Layer with AppSignals Support RUN wget https://github.com/aws-observability/aws-otel-js-instrumentation/ releases/latest/download/layer.zip -O /tmp/layer.zip # Extract and include Lambda layer contents RUN mkdir -p /opt && \ unzip /tmp/layer.zip -d /opt/ && \ chmod -R 755 /opt/ && \ rm /tmp/layer.zip # Install npm dependencies RUN npm init -y RUN npm install # Copy function code COPY *.js ${LAMBDA_TASK_ROOT}/ # Set the CMD to your handler CMD [ "index.handler" ] Note The layer.zip file contains the OpenTelemetry instrumentation necessary for AWS Application Signals support to monitor your Lambda function. The layer extraction steps ensures: • The layer.zip contents are properly extracted to the /opt/ directory • The otel-instrument script receives proper execution permissions • The temporary layer.zip file is removed to keep the image size smaller 3. Lambda function code Create an index.js file with the following content: const { S3Client, ListBucketsCommand } = require('@aws-sdk/client-s3'); // Initialize S3 client const s3Client = new S3Client({ region: process.env.AWS_REGION }); exports.handler = async function(event, context) { Enable your applications on Lambda 1479 Amazon CloudWatch User Guide console.log('Received event:', JSON.stringify(event, null, 2)); console.log('Handler initializing:', exports.handler.name); const response = { statusCode: 200, body: {} }; try { // List S3 buckets const command = new ListBucketsCommand({}); const data = await s3Client.send(command); // Extract bucket names const bucketNames = data.Buckets.map(bucket => bucket.Name); response.body = { message: 'Successfully retrieved buckets', buckets: bucketNames }; } catch (error) { console.error('Error listing buckets:', error); response.statusCode = 500; response.body = { message: `Error listing buckets: ${error.message}` }; } return response; }; Your project structure should look something like this: . ### Dockerfile ### index.js 4. Build and deploy the container image Set up environment variables Enable your applications on Lambda 1480 Amazon CloudWatch User Guide AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region)
acw-ug-395
acw-ug.pdf
395
= { message: 'Successfully retrieved buckets', buckets: bucketNames }; } catch (error) { console.error('Error listing buckets:', error); response.statusCode = 500; response.body = { message: `Error listing buckets: ${error.message}` }; } return response; }; Your project structure should look something like this: . ### Dockerfile ### index.js 4. Build and deploy the container image Set up environment variables Enable your applications on Lambda 1480 Amazon CloudWatch User Guide AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region) Authenticate with public Amazon ECR aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws Authenticate with private Amazon ECR aws ecr get-login-password --region $AWS_REGION | docker login --username AWS -- password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com Create Amazon ECR repository (if needed) aws ecr create-repository \ --repository-name lambda-appsignals-demo \ --region $AWS_REGION Build, tag, and push your image # Build the Docker image docker build -t lambda-appsignals-demo . # Tag the image docker tag lambda-appsignals-demo:latest $AWS_ACCOUNT_ID.dkr.ecr. $AWS_REGION.amazonaws.com/lambda-appsignals-demo:latest # Push the image docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/lambda-appsignals- demo:latest 5. Create and Configure the Lambda Function Enable your applications on Lambda 1481 Amazon CloudWatch User Guide 5. Create and configure the Lambda function Create a new function using the Lambda console. Select Container image as the deployment option. Choose Browse images to select your Amazon ECR image. 6. Testing and verifications – Test your Lambda with a simple event. If the layer integration is successful, your Lambda appears under the Application Signals service map. You will see traces and metrics for your Lambda function in the CloudWatch console. Troubleshooting If Application Signals is not working, check the following: • Check the function logs for any errors related to the OpenTelemetry instrumentation • Verify if the environment variable AWS_LAMBDA_EXEC_WRAPPER is set correctly • Make sure the layer extraction in the Docker file completed successfully • Confirm if the IAM permissions are properly attached • If needed, increase the Timeout and Memory settings in the general configuration of the Lambda function Python You can learn how to integrate the OpenTelemetry Layer with Application Signals support into your containerized Python Lambda function, download the layer.zip artifact, and integrate it into your Python Lambda function to enable Application Signals monitoring. Prerequisites • AWS CLI configured with your credentials • Docker installed • These instructions assume you are on x86_64 platform 1. Set Up Project Structure Create a directory for your Lambda function container image Enable your applications on Lambda 1482 Amazon CloudWatch User Guide mkdir python-appsignals-container-lambda &&\ cd python-appsignals-container-lambda 2. Create Dockerfile Download and integrate the OpenTelemetry Layer with Application Signals support directly into your Lambda container image. To do this, the Dockerfile file is created. Note The layer.zip file contains the OpenTelemetry instrumentation necessary for AWS Application Signals support to monitor your Lambda function. The layer extraction steps ensures: • The layer.zip contents are properly extracted to the /opt/ directory • The otel-instrument script receives proper execution permissions • The temporary layer.zip file is removed to keep the image size smaller 3. Lambda function code Create your Lambda function in an app.py file: import json import boto3 def lambda_handler(event, context): """ Sample Lambda function that can be used in a container image. Parameters: ----------- event: dict Input event data context: LambdaContext Lambda runtime information Returns: __ dict Response object Enable your applications on Lambda 1483 Amazon CloudWatch """ print("Received event:", json.dumps(event, indent=2)) User Guide # Create S3 client s3 = boto3.client('s3') try: # List buckets response = s3.list_buckets() # Extract bucket names buckets = [bucket['Name'] for bucket in response['Buckets']] return { 'statusCode': 200, 'body': json.dumps({ 'message': 'Successfully retrieved buckets', 'buckets': buckets }) } except Exception as e: print(f"Error listing buckets: {str(e)}") return { 'statusCode': 500, 'body': json.dumps({ 'message': f'Error listing buckets: {str(e)}' }) } Your project structure should look something like this: . ### Dockerfile ### app.py ### instructions.md 4. Build and deploy the container image Set up environment variables AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) AWS_REGION=$(aws configure get region) Enable your applications on Lambda 1484 Amazon CloudWatch User Guide # For fish shell users: # set AWS_ACCOUNT_ID (aws sts get-caller-identity --query Account --output text) # set AWS_REGION (aws configure get region) Authenticate with public Amazon ECR aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws Authenticate with private Amazon ECR aws ecr get-login-password --region $AWS_REGION | docker login --username AWS -- password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com Create Amazon ECR repository (if needed) aws ecr create-repository \ --repository-name lambda-appsignals-demo \ --region $AWS_REGION Build, tag, and push your image # Build the Docker image docker build -t lambda-appsignals-demo . # Tag the image docker tag lambda-appsignals-demo:latest $AWS_ACCOUNT_ID.dkr.ecr. $AWS_REGION.amazonaws.com/lambda-appsignals-demo:latest # Push the image docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/lambda-appsignals- demo:latest 5. Create and Configure the Lambda Function 5. Create and configure the Lambda
acw-ug-396
acw-ug.pdf
396
(aws configure get region) Authenticate with public Amazon ECR aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws Authenticate with private Amazon ECR aws ecr get-login-password --region $AWS_REGION | docker login --username AWS -- password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com Create Amazon ECR repository (if needed) aws ecr create-repository \ --repository-name lambda-appsignals-demo \ --region $AWS_REGION Build, tag, and push your image # Build the Docker image docker build -t lambda-appsignals-demo . # Tag the image docker tag lambda-appsignals-demo:latest $AWS_ACCOUNT_ID.dkr.ecr. $AWS_REGION.amazonaws.com/lambda-appsignals-demo:latest # Push the image docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/lambda-appsignals- demo:latest 5. Create and Configure the Lambda Function 5. Create and configure the Lambda function Create a new function using the Lambda console. Enable your applications on Lambda 1485 Amazon CloudWatch User Guide Select Container image as the deployment option. Choose Browse images to select your Amazon ECR image. 6. Testing and verifications – Test your Lambda with a simple event. If the layer integration is successful, your Lambda appears under the Application Signals service map. You will see traces and metrics for your Lambda function in the CloudWatch console. Troubleshooting If Application Signals is not working, check the following: • Check the function logs for any errors related to the OpenTelemetry instrumentation • Verify if the environment variable AWS_LAMBDA_EXEC_WRAPPER is set correctly • Make sure the layer extraction in the Docker file completed successfully • Confirm if the IAM permissions are properly attached • If needed, increase the Timeout and Memory settings in the general configuration of the Lambda function Troubleshooting your Application Signals installation This section contains troubleshooting tips for CloudWatch Application Signals. Topics • Application Signals Java layer cold start performance • Application doesn't start after Application Signals is enabled • Python application doesn't start after Application Signals is enabled • No Application Signals data for Python application that uses a WSGI server • My Node.js application is not instrumented or isn't generating Application Signals telemetry • No application data in Application Signals dashboard • Service metrics or dependency metrics have Unknown values • Handling a ConfigurationConflict when managing the Amazon CloudWatch Observability EKS add-on Troubleshooting your Application Signals installation 1486 Amazon CloudWatch User Guide • I want to filter out unnecessary metrics and traces • What does InternalOperation mean? • How do I enable logging for .NET applications? • How can I resolve assembly version conflicts in .NET applications? • Can I disable FluentBit? • Can I filter container logs before exporting to CloudWatch Logs? • Update to required versions of agents or Amazon EKS add-on Application Signals Java layer cold start performance Adding the Application Signals Layer to Java Lambda functions increases the startup latency (cold start time). The following tips can help reduce latency for time-sensitive functions. Fast startup for Java agent – The Application Signals Java Lambda Layer includes a Fast Startup feature that's turned off by default but can be enabled by setting the OTEL_JAVA_AGENT_FAST_STARTUP_ENABLED variable to true. When enabled, this feature configures the JVM to use tiered compilation level 1 C1 compiler to generate quick optimized native code for faster cold starts. The C1 compiler prioritizes speed at the cost of long-term optimization whereas the C2 compiler provides superior overall performance by profiling data over time. For more information, see Fast startup for Java agent . Reduce cold start times with Provisioned Concurrency – AWS Lambda provisioned concurrency pre-allocates a specified number of function instances, keeping them initialized and ready to handle requests immediately. This reduces cold-start times by eliminating the need to initialize the function environment during execution, ensuring faster and more consistent performance, especially for latency-sensitive workloads. For more information, see Configuring provisioned concurrency for a function . Optimize startup performance using Lambda SnapStart – AWS Lambda SnapStart is a feature that optimizes the startup performance of Lambda functions by creating a pre-initialized snapshot of the execution environment after the function's initialization phase. This snapshot is then reused to start new instances, significantly reducing cold-start times by skipping the initialization process during function invocation. For information, see Improving startup performance with Lambda SnapStart Troubleshooting your Application Signals installation 1487 Amazon CloudWatch User Guide Application doesn't start after Application Signals is enabled If your application on an Amazon EKS cluster doesn't start after you enable Application Signals on the cluster, check for the following: • Check if the application has been instrumented by another monitoring solution. Application Signals might not support co-existing with other instrumentation solutions. • Confirm that your the application meets the compatibility requirements to use Application Signals. For more information, see Supported systems. • If your application failed to pull the Application Signals artifacts such as the AWS Distro for OpenTelemetery Java or Python agent and CloudWatch agent images, it could be a network issue. To mitigate the issue, remove the annotation instrumentation.opentelemetry.io/inject- java: "true" or instrumentation.opentelemetry.io/inject-python: "true" from your application
acw-ug-397
acw-ug.pdf
397
enable Application Signals on the cluster, check for the following: • Check if the application has been instrumented by another monitoring solution. Application Signals might not support co-existing with other instrumentation solutions. • Confirm that your the application meets the compatibility requirements to use Application Signals. For more information, see Supported systems. • If your application failed to pull the Application Signals artifacts such as the AWS Distro for OpenTelemetery Java or Python agent and CloudWatch agent images, it could be a network issue. To mitigate the issue, remove the annotation instrumentation.opentelemetry.io/inject- java: "true" or instrumentation.opentelemetry.io/inject-python: "true" from your application deployment manifest, and re-deploy your application. Then check if the application is working. Known issues The runtime metrics collection in the Java SDK release v1.32.5 is known to not work with applications using JBoss Wildfly. This issue extends to the Amazon CloudWatch Observability EKS add-on, affecting versions 2.3.0-eksbuild.1 through 2.5.0-eksbuild.1. If you are impacted, either downgrade the version or disable your runtime metrics collection by adding the environment variable OTEL_AWS_APPLICATION_SIGNALS_RUNTIME_ENABLED=false to your application. Python application doesn't start after Application Signals is enabled It is a known issue in OpenTelemetry auto-instrumentation that a missing PYTHONPATH environment variable can sometimes cause the application to fail to start . To resolve this, ensure that you set the PYTHONPATH environment variable to the location of your application’s working directory. For more information about this issue, see Python autoinstrumentation setting of PYTHONPATH is not compliant with Python's module resolution behavior, breaking Django applications. For Django applications, there are additional required configurations, which are outlined in the OpenTelemetry Python documentation. Troubleshooting your Application Signals installation 1488 Amazon CloudWatch User Guide • Use the --noreload flag to prevent automatic reloading. • Set the DJANGO_SETTINGS_MODULE environment variable to the location of your Django application’s settings.py file. This ensures that OpenTelemetry can correctly access and integrate with your Django settings. No Application Signals data for Python application that uses a WSGI server If you are using a WSGI server such as Gunicorn or uWSGI, you must make additional changes to make the ADOT Python auto-instrumentation work. Note Be sure that you are using the latest version of ADOT Python and the Amazon CloudWatch Observability EKS add-on before proceeding. Additional steps to enable Application Signals with a WSGI server 1. Import the auto-instrumentation in the forked worker processes. For Gunicorn, use the post_fork hook: # gunicorn.conf.py def post_fork(server, worker): from opentelemetry.instrumentation.auto_instrumentation import sitecustomize For uWSGI, use the import directive. # uwsgi.ini [uwsgi] ; required for the instrumentation of worker processes enable-threads = true lazy-apps = true import = opentelemetry.instrumentation.auto_instrumentation.sitecustomize 2. Enable the configuration for ADOT Python auto-instrumentation to skip the main process and defer to workers by setting the OTEL_AWS_PYTHON_DEFER_TO_WORKERS_ENABLED environment variable to true. Troubleshooting your Application Signals installation 1489 Amazon CloudWatch User Guide My Node.js application is not instrumented or isn't generating Application Signals telemetry To enable Application Signals for Node.js, you must ensure that your Node.js application uses the CommonJS (CJS) module format. Currently, the AWS Distro for OpenTelemetry Node.js doesn't support the ESM module format, because OpenTelemetry JavaScript’s support of ESM is experimental and is a work in progress. To determine if your application is using CJS and not ESM, ensure that your application does not fulfill the conditions to enable ESM. No application data in Application Signals dashboard If metrics or traces are missing in the Application Signals dashboards, the following might be causes. Investigate these causes only if you have waited 15 minutes for Application Signals to collect and display data since your last update. • Make sure that your library and framework you are using is supported by the ADOT Java agent. For more information, see Libraries / Frameworks. • Make sure that the CloudWatch agent is running. First check the status of the CloudWatch agent pods and make sure they are all in Running status. kubectl -n amazon-cloudwatch get pods. Add the following to the CloudWatch agent configuration file to enable debugging logs, and then restart the agent. "agent": { "region": "${REGION}", "debug": true }, Then check for errors in the CloudWatch agent pods. • Check for configuration issues with the CloudWatch agent. Confirm that the following is still in the CloudWatch agent configuration file and the agent has been restarted since it was added. "agent": { Troubleshooting your Application Signals installation 1490 Amazon CloudWatch User Guide "region": "${REGION}", "debug": true }, Then check the OpenTelemetry debugging logs for error messages such as ERROR io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporter - Failed to export .... These messages might indicate the problem. If that doesn't solve the issue, dump and check the environment variables with names that start with OTEL_ by describing the pod with the kubectl describe pod command. • To enable the OpenTelemetry Python debug logging, set the environment variable OTEL_PYTHON_LOG_LEVEL to debug and redeploy the application.
acw-ug-398
acw-ug.pdf
398
configuration file and the agent has been restarted since it was added. "agent": { Troubleshooting your Application Signals installation 1490 Amazon CloudWatch User Guide "region": "${REGION}", "debug": true }, Then check the OpenTelemetry debugging logs for error messages such as ERROR io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporter - Failed to export .... These messages might indicate the problem. If that doesn't solve the issue, dump and check the environment variables with names that start with OTEL_ by describing the pod with the kubectl describe pod command. • To enable the OpenTelemetry Python debug logging, set the environment variable OTEL_PYTHON_LOG_LEVEL to debug and redeploy the application. • Check for wrong or insufficient permissions for exporting data from the CloudWatch agent. If you see Access Denied messages in the CloudWatch agent logs, this might be the issue. It is possible that the permissions applied when you installed the CloudWatch agent were later changed or revoked. • Check for an AWS Distro for OpenTelemetry (ADOT) issue when generating telemetry data. Make sure that the instrumentation annotations instrumentation.opentelemetry.io/ inject-java and sidecar.opentelemetry.io/inject-java are applied to the application deployment and the value is true. Without these, the application pods will not be instrumented even if the ADOT addon is installed correctly. Next, check if the init container is applied on the application and the Ready state is True. If the init container is not ready, see the status for the reason. If the issue persists, enable debug logging on the OpenTelemetry Java SDK by setting the environment variable OTEL_JAVAAGENT_DEBUG to true and redeploying the application. Then look for messages that start with ERROR io.telemetry. • The metric/span exporter might be dropping data. To find out, check the application log for messages that include Failed to export... • The CloudWatch agent might be getting throttled when sending metrics or spans to Application Signals. Check for messages indicating throttling in the CloudWatch agent logs. • Make sure that you've enabled the service discovery setup. You need to do this only once in your Region. Troubleshooting your Application Signals installation 1491 Amazon CloudWatch User Guide To confirm this, in the CloudWatch console choose Application Signals, Services. If Step 1 is not marked Complete, choose Start discovering your services. Data should start flowing in within five minutes. Service metrics or dependency metrics have Unknown values If you see UnknownService, UnknownOperation, UnknownRemoteService, or UnknownRemoteOperation for a dependency name or operation in the Application Signals dashboards, check whether the occurrence of data points for the unknown remote service and unknown remote operation are coinciding with their deployments. • UnknownService means that the name of an instrumented application is unknown. If the OTEL_SERVICE_NAME environment variable is undefined and service.name isn't specified in OTEL_RESOURCE_ATTRIBUTES, the service name is set to UnknownService. To fix this, specify the service name in OTEL_SERVICE_NAME or OTEL_RESOURCE_ATTRIBUTES. • UnknownOperation means that the name of an invoked operation is unknown. This occurs when Application Signals is unable to discover an operation name which invokes the remote call, or when the extracted operation name contains high cardinality values. • UnknownRemoteService means that the name of the destination service is unknown. This occurs when the system is unable to extract the destination service name that the remote call accesses. One solution is to create a custom span around the function that sends out the request, and add the attribute aws.remote.service with the designated value. Another option is to configure the CloudWatch agent to customize the metric value of RemoteService. For more information about customizations in the CloudWatch agent, see Enable CloudWatch Application Signals. • UnknownRemoteOperation means that the name of the destination operation is unknown. This occurs when the system is unable to extract the destination operation name that the remote call accesses. One solution is to create a custom span around the function that sends out the request, and add the attribute aws.remote.operation with the designated value. Another option is to configure the CloudWatch agent to customize the metric value of RemoteOperation. For more information about customizations in the CloudWatch agent, see Enable CloudWatch Application Signals. Troubleshooting your Application Signals installation 1492 Amazon CloudWatch User Guide Handling a ConfigurationConflict when managing the Amazon CloudWatch Observability EKS add-on When you install or update the Amazon CloudWatch Observability EKS add-on, if you notice a failure caused by a Health Issue of type ConfigurationConflict with a description that starts with Conflicts found when trying to apply. Will not continue due to resolve conflicts mode, it is likely because you already have the CloudWatch agent and its associated components such as the ServiceAccount, the ClusterRole and the ClusterRoleBinding installed on the cluster. When the add-on tries to install the CloudWatch agent and its associated components, if it detects any change in the contents, it by default fails the installation or update to avoid overwriting the state of the resources on
acw-ug-399
acw-ug.pdf
399
EKS add-on, if you notice a failure caused by a Health Issue of type ConfigurationConflict with a description that starts with Conflicts found when trying to apply. Will not continue due to resolve conflicts mode, it is likely because you already have the CloudWatch agent and its associated components such as the ServiceAccount, the ClusterRole and the ClusterRoleBinding installed on the cluster. When the add-on tries to install the CloudWatch agent and its associated components, if it detects any change in the contents, it by default fails the installation or update to avoid overwriting the state of the resources on the cluster. If you are trying to onboard to the Amazon CloudWatch Observability EKS add-on and you see this failure, we recommend deleting an existing CloudWatch agent setup that you had previously installed on the cluster and then installing the EKS add-on. Be sure to back up any customizations you might have made to the original CloudWatch agent setup such as a custom agent configuration, and provide these to the Amazon CloudWatch Observability EKS add-on when you next install or update it. If you had previously installed the CloudWatch agent for onboarding to Container Insights, see Deleting the CloudWatch agent and Fluent Bit for Container Insights for more information. Alternatively, the add-on supports a conflict resolution configuration option that has the capability to specify OVERWRITE. You can use this option to proceed with installing or updating the add-on by overwriting the conflicts on the cluster. If you are using the Amazon EKS console, you'll find the Conflict resolution method when you choose the Optional configuration settings when you create or update the add-on. If you are using the AWS CLI, you can supply the --resolve- conflicts OVERWRITE to your command to create or update the add-on. I want to filter out unnecessary metrics and traces If Application Signals is collecting traces and metrics that you don't want, see Manage high- cardinality operations for information about configuring the CloudWatch agent with custom rules to reduce cardinality. For information about customizing trace sampling rules, see Configure sampling rules in the X-Ray documentation. Troubleshooting your Application Signals installation 1493 Amazon CloudWatch User Guide What does InternalOperation mean? An InternalOperation is an operation that is triggered by the application internally rather than by an external invocation. Seeing InternalOperation is expected, healthy behavior. Some typical examples where you would see InternalOperation include the following: • Preloading on start– Your application performs an operation named loadDatafromDB which reads metadata from a database during the warm up phase. Instead of observing loadDatafromDB as a service operation, you'll see it categorized as an InternalOperation. • Async execution in the background– Your application subscribes to an event queue, and processes streaming data accordingly whenever there’s an update. Each triggered operation will be under InternalOperation as a service operation. • Retrieving host information from a service registry– Your application talks to a service registry for service discovery. All interactions with the discovery system are classified as an InternalOperation. How do I enable logging for .NET applications? To enable logging for .NET applications, configure the following environment variables. For more information about how to configure these environment variables, see Troubleshooting .NET automatic instrumentation issues in the OpenTelemetry documentation. • OTEL_LOG_LEVEL • OTEL_DOTNET_AUTO_LOG_DIRECTORY • COREHOST_TRACE • COREHOST_TRACEFILE How can I resolve assembly version conflicts in .NET applications? If you get the following error, see Assembly version conflicts in the OpenTelemetry documentation for resolution steps. Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified. Troubleshooting your Application Signals installation 1494 Amazon CloudWatch User Guide File name: 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' at Microsoft.AspNetCore.Builder.WebApplicationBuilder..ctor(WebApplicationOptions options, Action`1 configureDefaults) at Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(String[] args) at Program.<Main>$(String[] args) in /Blog.Core/Blog.Core.Api/Program.cs:line 26 Can I disable FluentBit? You can disable FluentBit by configuring the Amazon CloudWatch Observability EKS add-on. For more information, see (Optional) Additional configuration. Can I filter container logs before exporting to CloudWatch Logs? No, filtering container logs is not yet supported. Update to required versions of agents or Amazon EKS add-on After August 9, 2024, CloudWatch Application Signals will no longer support older versions of the Amazon CloudWatch Observability EKS add-on, the CloudWatch agent, and the AWS Distro for OpenTelemetry auto-instrumentation agent. • For the Amazon CloudWatch Observability EKS add-on, versions older than v1.7.0- eksbuild.1 won't be supported. • For the CloudWatch agent, versions older than 1.300040.0 won't be supported. • For the AWS Distro for OpenTelemetry auto-instrumentation agent: • For Java, versions older than 1.32.2 aren't supported. • For Python, versions older than 0.2.0 aren't supported. • For .NET, versions older than 1.3.2 aren't supported. • For Node.js, versions older than 0.3.0 aren't supported. Important The latest versions of the agents include updates to the Application Signals metric schema. These updates are not backward compatible, and this
acw-ug-400
acw-ug.pdf
400
for OpenTelemetry auto-instrumentation agent. • For the Amazon CloudWatch Observability EKS add-on, versions older than v1.7.0- eksbuild.1 won't be supported. • For the CloudWatch agent, versions older than 1.300040.0 won't be supported. • For the AWS Distro for OpenTelemetry auto-instrumentation agent: • For Java, versions older than 1.32.2 aren't supported. • For Python, versions older than 0.2.0 aren't supported. • For .NET, versions older than 1.3.2 aren't supported. • For Node.js, versions older than 0.3.0 aren't supported. Important The latest versions of the agents include updates to the Application Signals metric schema. These updates are not backward compatible, and this can result in data issues if incompatible versions are used. To help ensure a seamless transition to the new functionality, do the following: Troubleshooting your Application Signals installation 1495 Amazon CloudWatch User Guide • If your application is running on Amazon EKS, be sure to restart all instrumented applications after you update the Amazon CloudWatch Observability add-on. • For applications running on other platforms, be sure to upgrade both the CloudWatch agent and the AWS OpenTelemetry auto-instrumentation agent to the latest versions. The instructions in the following sections can help you update to a supported version. Contents • Update the Amazon CloudWatch Observability EKS add-on • Use the console • Use the AWS CLI • Update the CloudWatch agent and ADOT agent • Update on Amazon ECS • Update on Amazon EC2 or other architectures Update the Amazon CloudWatch Observability EKS add-on To the Amazon CloudWatch Observability EKS add-on, you can use the AWS Management Console or the AWS CLI. Use the console To upgrade the add-on using the console 1. Open the Amazon EKS console at https://console.aws.amazon.com/eks/home#/clusters. 2. Choose the name of the Amazon EKS cluster to update. 3. Choose the Add-ons tab, then choose Amazon CloudWatch Observability. 4. Choose Edit, select the version you want to update to, and then choose Save changes. Be sure to choose v1.7.0-eksbuild.1 or later. 5. Enter one of the following AWS CLI commands to restart your services. # Restart a deployment kubectl rollout restart deployment/name # Restart a daemonset Troubleshooting your Application Signals installation 1496 Amazon CloudWatch User Guide kubectl rollout restart daemonset/name # Restart a statefulset kubectl rollout restart statefulset/name Use the AWS CLI To upgrade the add-on using the AWS CLI 1. Enter the following command to find the latest version. aws eks describe-addon-versions \ --addon-name amazon-cloudwatch-observability 2. Enter the following command to update the add-on. Replace $VERSION with a version that is v1.7.0-eksbuild.1 or later. Replace $AWS_REGION and $CLUSTER with your Region and cluster name. aws eks update-addon \ --region $AWS_REGION \ --cluster-name $CLUSTER \ --addon-name amazon-cloudwatch-observability \ --addon-version $VERSION \ # required only if the advanced configuration is used. --configuration-values $JSON_CONFIG Note If you're using an custom configuration for the add-on, you can find an example of the configuration to use for $JSON_CONFIG in Enable CloudWatch Application Signals. 3. Enter one of the following AWS CLI commands to restart your services. # Restart a deployment kubectl rollout restart deployment/name # Restart a daemonset kubectl rollout restart daemonset/name # Restart a statefulset kubectl rollout restart statefulset/name Troubleshooting your Application Signals installation 1497 Amazon CloudWatch User Guide Update the CloudWatch agent and ADOT agent If your services are running on architectures other than Amazon EKS, you will need to upgrade both the CloudWatch agent and the ADOT auto-instrumentation agent to use the latest Application Signals features. Update on Amazon ECS To upgrade your agents for services running on Amazon ECS 1. Create a new task definition revision. For more information, see Updating a task definition using the console. 2. Replace the $IMAGE of the ecs-cwagent container with the latest image tag from cloudwatch-agent on Amazon ECR. If you upgrade to a fixed version, be sure to use a version equal to or later than 1.300040.0. 3. Replace the $IMAGE of the init container with the latest image tag from the following locations: • For Java, use aws-observability/adot-autoinstrumentation-java. If you upgrade to a fixed version, be sure to use a version equal to or later than 1.32.2. • For Python, use aws-observability/adot-autoinstrumentation-python. If you upgrade to a fixed version, be sure to use a version equal to or later than 0.2.0. • For .NET, use aws-observability/adot-autoinstrumentation-dotnet. If you upgrade to a fixed version, be sure to use a version equal to or later than 1.3.2. • For Node.js, use aws-observability/adot-autoinstrumentation-node. If you upgrade to a fixed version, be sure to use a version equal to or later than 0.3.0. 4. Update the Application Signals environment variables in your app container by following the instructions at Step 4: Instrument your application with the CloudWatch agent. 5. Deploy your service with the new task definition. Troubleshooting your Application Signals installation 1498 Amazon CloudWatch User Guide Update on Amazon EC2 or other architectures To
acw-ug-401
acw-ug.pdf
401
• For .NET, use aws-observability/adot-autoinstrumentation-dotnet. If you upgrade to a fixed version, be sure to use a version equal to or later than 1.3.2. • For Node.js, use aws-observability/adot-autoinstrumentation-node. If you upgrade to a fixed version, be sure to use a version equal to or later than 0.3.0. 4. Update the Application Signals environment variables in your app container by following the instructions at Step 4: Instrument your application with the CloudWatch agent. 5. Deploy your service with the new task definition. Troubleshooting your Application Signals installation 1498 Amazon CloudWatch User Guide Update on Amazon EC2 or other architectures To upgrade your agents for services running on Amazon EC2 or other architectures 1. Follow the instructions at Download the CloudWatch agent package and upgrade the CloudWatch agent to the latest version. Be sure to select version 1.300040.0 or later. 2. Download the latest version of the AWS Distro for OpenTelemetry auto-instrumentation agent from one of the following locations: • For Java, use aws-otel-java-instrumentation . If you upgrade to a fixed version, be sure to choose 1.32.2 or later. • For Python, use aws-otel-python-instrumentation . If you upgrade to a fixed version, be sure to choose 0.2.0 or later. • For .NET, use aws-otel-dotnet-instrumentation. If you upgrade to a fixed version, be sure to choose 1.3.2 or later. • For Node.js, use aws-otel-js-instrumentation . If you upgrade to a fixed version, be sure to choose 0.3.0 or later. 3. Apply the updated Application Signals environment variables to your application, then start your application. For more information, see Step 3: Instrument your application and start it. (Optional) Configuring Application Signals This section contains information about configuring CloudWatch Application Signals. Topics • Trace sampling rate • Enable trace to log correlation • Enable metric to log correlation • Manage high-cardinality operations (Optional) Configuring Application Signals 1499 Amazon CloudWatch Trace sampling rate User Guide By default, when you enable Application Signals X-Ray centralized sampling is enabled using the default sampling rate settings of reservoir=1/s and fixed_rate=5%. The environment variables for the AWS Distro for OpenTelemetry (ADOT) SDK agent as set as follows. Environment variable Value Note OTEL_TRACES_SAMPLER xray OTEL_TRACES_SAMPLE endpoint=http://cl R_ARG oudwatch-agent.ama zon-cloudwatch:2000 Endpoint of the CloudWatch agent For information about changing the sampling configuration, see the following: • To change X-Ray sampling, see Configure sampling rules • To change ADOT sampling, see Configuring the OpenTelemetry Collector for X-Ray remote sampling If you want to disable X-Ray centralized sampling and use local sampling instead, set the following values for the ADOT SDK Java agent as below. The following example sets the sampling rate at 5%. Environment variable Value OTEL_TRACES_SAMPLER parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG 0.05 For information about more advanced sampling settings, see OTEL_TRACES_SAMPLER. Enable trace to log correlation You can enable trace to log correlation in Application Signals. This automatically injects trace IDs and span IDs into the relevant application logs. Then, when you open a trace detail page in the Application Signals console, the relevant log entries (if any) that correlate with the current trace automatically appear at the bottom of the page. (Optional) Configuring Application Signals 1500 Amazon CloudWatch User Guide For example, suppose you notice a spike in a latency graph. You can choose the point on the graph to load the diagnostics information for that point in time. You then choose the relevant trace to get more information. When you view the trace information, you can scroll down to see the logs associated with the trace. These logs might reveal patterns or error codes associated with the issues causing the latency spike. To achieve trace log correlation, Application Signals relies on the following: • Logger MDC auto-instrumentation for Java. • OpenTelemetry Logging Instrumentation for Python. • The Pino, Winston, or Bunyan auto-instrumentations for Node.js. All of these isntrumentations are provided by OpenTelemetry community. Application Signals uses them to inject trace contexts such as trace ID and span ID into application logs. To enable this, you must manually change your logging configuration to enable the auto-instrumentation. Depending on the architecture that your application runs on, you might have to also set an environment variable to enable trace log correlation, in addition to following the steps in this section. • On Amazon EKS, no further steps are needed. • On Amazon ECS, no further steps are needed. • On Amazon EC2, see the step 4 in the procedure in Step 3: Instrument your application and start it. After you enable trace log correlation, Trace log correlation setup examples This section contains examples of setting up trace log correlation in several environments. Spring Boot for Java Suppose you have a Spring Boot application in a folder called custom-app. The application configuration is usually a YAML file named custom-app/src/main/resources/ application.yml that might look like this: spring: (Optional) Configuring Application Signals 1501 User Guide Amazon CloudWatch application:
acw-ug-402
acw-ug.pdf
402
further steps are needed. • On Amazon ECS, no further steps are needed. • On Amazon EC2, see the step 4 in the procedure in Step 3: Instrument your application and start it. After you enable trace log correlation, Trace log correlation setup examples This section contains examples of setting up trace log correlation in several environments. Spring Boot for Java Suppose you have a Spring Boot application in a folder called custom-app. The application configuration is usually a YAML file named custom-app/src/main/resources/ application.yml that might look like this: spring: (Optional) Configuring Application Signals 1501 User Guide Amazon CloudWatch application: name: custom-app config: import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} ... To enable trace log correlation, add the following logging configuration. spring: application: name: custom-app config: import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/} ... logging: pattern: level: trace_id=%mdc{trace_id} span_id=%mdc{span_id} trace_flags=%mdc{trace_flags} %5p Logback for Java In the logging configuration (such as logback.xml), insert the trace context trace_id= %mdc{trace_id} span_id=%mdc{span_id} trace_flags=%mdc{trace_flags} %5p into pattern of Encoder. For example, the following configuration prepends the trace context before the log message. <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>app.log</file> <append>true</append> <encoder> <pattern>trace_id=%mdc{trace_id} span_id=%mdc{span_id} trace_flags= %mdc{trace_flags} %5p - %m%n</pattern> </encoder> </appender> For more information about encoders in Logback, see Encoders in the Logback documentation. Log4j2 for Java (Optional) Configuring Application Signals 1502 Amazon CloudWatch User Guide In the logging configuration (such as log4j2.xml), insert the trace context trace_id= %mdc{trace_id} span_id=%mdc{span_id} trace_flags=%mdc{trace_flags} %5p into PatternLayout. For example, the following configuration prepends the trace context before the log message. <Appenders> <File name="FILE" fileName="app.log"> <PatternLayout pattern="trace_id=%mdc{trace_id} span_id=%mdc{span_id} trace_flags= %mdc{trace_flags} %5p - %m%n"/> </File> </Appenders> For more information about pattern layouts in Log4j2, see Pattern Layout in the Log4j2 documentation. Log4j for Java In the logging configuration (such as log4j.xml), insert the trace context trace_id= %mdc{trace_id} span_id=%mdc{span_id} trace_flags=%mdc{trace_flags} %5p into PatternLayout. For example, the following configuration prepends the trace context before the log message. <appender name="FILE" class="org.apache.log4j.FileAppender">; <param name="File" value="app.log"/>; <param name="Append" value="true"/>; <layout class="org.apache.log4j.PatternLayout">; <param name="ConversionPattern" value="trace_id=%mdc{trace_id} span_id= %mdc{span_id} trace_flags=%mdc{trace_flags} %5p - %m%n"/>; </layout>; </appender>; For more information about pattern layouts in Log4j, see Class Pattern Layout in the Log4j documentation. Python Set the environment variable OTEL_PYTHON_LOG_CORRELATION to true while running your application. For more information, see Enable trace context injectionin the Python OpenTelemetry documentation. Node.js (Optional) Configuring Application Signals 1503 Amazon CloudWatch User Guide For more information about enabling trace context injection in Node.js for the logging libraries that support it, see the NPM usage documentations of the Pino, Winston, or Bunyan auto- instrumentations for Node.js. Enable metric to log correlation If you publish application logs to log groups in CloudWatch Logs, you can enable metric to application log correlation in Application Signals. With metric log correlation, the Application Signals console automatically displays the relevant log groups associated with a metric. For example, suppose you notice a spike in a latency graph. You can choose a point on the graph to load the diagnostics information for that point in time. The diagnostics information will show the relevant application log groups that are associated with the current service and metric. Then you can choose a button to run a CloudWatch Logs Insights query on those log groups. Depending on the information contained in the application logs, this might help you to investigate the cause of the latency spike. Depending on the architecture that your application runs on, you might have to also set an environment variable to enable metric to application log correlation. • On Amazon EKS, no further steps are needed. • On Amazon ECS, no further steps are needed. • On Amazon EC2, see step 4 in the procedure in Step 3: Instrument your application and start it. Manage high-cardinality operations Application Signals includes settings in the CloudWatch agent that you can use to manage the cardinality of your operations and manage the metric exportation to optimize costs. By default, the metric limiting function becomes active when the number of distinct operations for a service over time exceeds the default threshold of 500. You can tune the behavior by adjusting the configuration settings. Determine if metric limiting is activated You can use the following methods to find if the default metric limiting is happening. If it is, you should consider optimizing the cardinality control by following the steps in the next section. (Optional) Configuring Application Signals 1504 Amazon CloudWatch User Guide • In the CloudWatch console, choose Application Signals, Services. If you see an Operation named AllOtherOperations or a RemoteOperation named AllOtherRemoteOperations, then metric limiting is happening. • If any metrics collected by Application Signals have the value AllOtherOperations for their Operation dimension, then metric limiting is happening. • If any metrics collected by Application Signals have the value AllOtherRemoteOperations for their RemoteOperation dimension, then metric limiting is happening. Optimize cardinality control To optimize your cardinality control, you can do the following: • Create custom rules to aggregate operations. •
acw-ug-403
acw-ug.pdf
403
next section. (Optional) Configuring Application Signals 1504 Amazon CloudWatch User Guide • In the CloudWatch console, choose Application Signals, Services. If you see an Operation named AllOtherOperations or a RemoteOperation named AllOtherRemoteOperations, then metric limiting is happening. • If any metrics collected by Application Signals have the value AllOtherOperations for their Operation dimension, then metric limiting is happening. • If any metrics collected by Application Signals have the value AllOtherRemoteOperations for their RemoteOperation dimension, then metric limiting is happening. Optimize cardinality control To optimize your cardinality control, you can do the following: • Create custom rules to aggregate operations. • Configure your metric limiting policy. Create custom rules to aggregate operations High-cardinality operations can sometimes be caused by inappropriate unique values extracted from the context. For example, sending out HTTP/S requests that include user IDs or session IDs in the path can lead to hundreds of disparate operations. To resolve such issues, we recommend that you configure the CloudWatch agent with customization rules to rewrite these operations. In cases where there is a surge in generating numerous different metrics through individual RemoteOperation calls, such as PUT /api/customer/owners/123, PUT /api/customer/ owners/456, and similar requests, we recommend that you consolidate these operations into a single RemoteOperation. One approach is to standardize all RemoteOperation calls that start with PUT /api/customer/owners/ to a uniform format, specifically PUT /api/customer/ owners/{ownerId}. The following example illustrates this. For information about other customization rules, see Enable CloudWatch Application Signals. { "logs":{ "metrics_collected":{ "application_signals":{ "rules":[ { "selectors":[ { (Optional) Configuring Application Signals 1505 Amazon CloudWatch User Guide "dimension":"RemoteOperation", "match":"PUT /api/customer/owners/*" } ], "replacements":[ { "target_dimension":"RemoteOperation", "value":"PUT /api/customer/owners/{ownerId}" } ], "action":"replace" } ] } } } } In other cases, high-cardinality metrics might have been aggregated to AllOtherRemoteOperations, and it might be unclear what specific metrics are included. The CloudWatch agent is able to log the dropped operations. To identify dropped operations, use the configuration in the following example to activate logging until the problem resurfaces. Then inspect the CloudWatch agent logs (accessible by container stdout or EC2 log files) and search for the keyword drop metric data. { "agent": { "config": { "agent": { "debug": true }, "traces": { "traces_collected": { "application_signals": { } } }, "logs": { "metrics_collected": { "application_signals": { "limiter": { "log_dropped_metrics": true (Optional) Configuring Application Signals 1506 Amazon CloudWatch } } } } } } } User Guide Create your metric limiting policy If the default metric limiting configuration doesn’t address the cardinality for your service, you can customize the metric limiter configuration. To do this, add a limiter section under the logs/ metrics_collected/application_signals section in the CloudWatch Agent configuration file. The following example lowers the threshold of metric limiting from 500 distinct metrics to 100. { "logs": { "metrics_collected": { "application_signals": { "limiter": { "drop_threshold": 100 } } } } } Monitor the operational health of your applications with Application Signals Use Application Signals within the CloudWatch console to monitor and troubleshoot the operational health of your applications: • Monitor your application services — As part of daily operational monitoring, use the Services page to see a summary of all your services. See services with the highest fault rate or latency, and see which services have unhealthy service level indicators (SLIs). Select a service to open the Service detail page and see detailed metrics, service operations, Synthetics canaries, and client requests. This can help you troubleshoot and identify the root cause of operational issues. Monitor your application's operational health 1507 Amazon CloudWatch User Guide • Inspect your application topology — Use the Service Map to understand and monitor your application topology over time, including the relationships between clients, Synthetics canaries, services, and dependencies. Instantly see service level indicator (SLI) health and view key metrics such as call volume, fault rate, and latency. Drill down to see more detailed information in the Service detail page. Explore an example scenario that demonstrates how these pages can be used to quickly troubleshoot an operational service health issue, from initial detection to identifying root cause. How Application Signals enables operational health monitoring After you enable your application for Application Signals, your application services, APIs, and their dependencies are automatically discovered and displayed in the Services, Service detail, and Service Map pages. Application Signals collects information from multiple sources to enable service discovery and operational health monitoring: • AWS Distro for OpenTelemetry (ADOT) — As part of enabling Application Signals, OpenTelemetry Java and Python auto-instrumentation libraries are configured to emit metrics and traces that are collected by the CloudWatch agent. The metrics and traces are used to enable discovery of services, operations, dependencies, and other service information. • Service-level objectives (SLOs) — After you create service level objectives for your services, the Services, Service detail, and Service Map pages display service level indicator (SLI) health. SLIs can monitor latency,
acw-ug-404
acw-ug.pdf
404
Service Map pages. Application Signals collects information from multiple sources to enable service discovery and operational health monitoring: • AWS Distro for OpenTelemetry (ADOT) — As part of enabling Application Signals, OpenTelemetry Java and Python auto-instrumentation libraries are configured to emit metrics and traces that are collected by the CloudWatch agent. The metrics and traces are used to enable discovery of services, operations, dependencies, and other service information. • Service-level objectives (SLOs) — After you create service level objectives for your services, the Services, Service detail, and Service Map pages display service level indicator (SLI) health. SLIs can monitor latency, availability, and other operational metrics. • CloudWatch Synthetics canaries — When you configure X-Ray tracing on your canaries, calls to your services from your canary scripts are associated with your service and displayed within the Service detail page. • CloudWatch Real user monitoring (RUM) — When X-Ray tracing is enabled on your CloudWatch RUM web client, requests to your services are automatically associated and displayed within the service detail page. • AWS Service Catalog AppRegistry — Application Signals auto-discovers AWS resources within your account and allows you to group them into logical applications created in AppRegistry. The application name displayed in the Services page is based on the underlying compute resource that your services are running on. Monitor your application's operational health 1508 Amazon CloudWatch Note User Guide Application Signals displays your services and operations based on metrics and traces emitted within the current time filter that you chose. (By default, this is the past three hours.) If there is no activity within the current time filter for a service, operation, dependency, Synthetics canary, or client page, it won't be displayed. Currently, up to 1,000 services can be displayed. Discovery of your services and service topology might be delayed up to 10 minutes. Evaluation of your service level indicator (SLI) health might be delayed up to 15 minutes. Note Application Signals console currently only supports choosing a maximum of one day within the 30 days time range. View overall service activity and operational health with the Services page Use the Services page to see a list of your services that are enabled for Application Signals. You can also view operational metrics and quickly see which services have unhealthy service level indicators (SLIs). Drill down to look for performance anomalies as you identify the root cause of operational issues. To view this page, open the CloudWatch console and choose Services under the Application Signals section in the left navigation pane. Explore operational health metrics for your services The top of the Services page includes an overall service operational health graph and several tables displaying top services and service dependencies by fault rate. The Services graph on the left displays a breakdown of the number of services that have healthy or unhealthy service level indicators (SLIs) during the current page-level time filter. SLIs can monitor latency, availability, and other operational metrics. The two tables next to the graph display a list of top services by fault rate. Choose any service name in either table to open a service detail page and see detailed service operation details. Choose a dependency path to open the detail page and see service dependency details. Both tables display information for up to the past three hours, even if a longer time period filter is chosen at the top right of the page. Monitor your application's operational health 1509 Amazon CloudWatch User Guide Monitor operational health with the Services table The Services table displays a list of your services that have been enabled for Application Signals. Choose Enable Application Signals to open a setup page and start configuring your services. For more information, see Enable Application Signals. Filter the Services table to make it easier to find what you're looking for, by choosing one or more properties from the filter text box. As you choose each property, you are guided through filter criteria. You will see the complete filter below the filter text box. Choose Clear filters at any time to remove the table filter. Choose the name of any service in the table to view a service detail page containing service- level metrics, operations, and additional details. If you have associated the service's underlying compute resource with an application in AppRegistry or the Applications card on the AWS Management Console home page, choose the application name to display the application details in the myApplications console page. For services hosted in Amazon EKS, choose any link within the Hosted in column to view Cluster, Namespace, or Workload within CloudWatch Container Insights. For services running on Amazon ECS or Amazon EC2, the Environment value is shown. Service level indicator (SLI) status is displayed for each service in the table. Choose the SLI status for a service to display a
acw-ug-405
acw-ug.pdf
405
If you have associated the service's underlying compute resource with an application in AppRegistry or the Applications card on the AWS Management Console home page, choose the application name to display the application details in the myApplications console page. For services hosted in Amazon EKS, choose any link within the Hosted in column to view Cluster, Namespace, or Workload within CloudWatch Container Insights. For services running on Amazon ECS or Amazon EC2, the Environment value is shown. Service level indicator (SLI) status is displayed for each service in the table. Choose the SLI status for a service to display a pop-up containing a link to any unhealthy SLIs, and a link to see all SLOs for the service. Monitor your application's operational health 1510 Amazon CloudWatch User Guide If no SLOs have been created for a service, choose the Create SLO button within the SLI Status column. To create additional SLOs for any service, select the option button next to the service name, and then choose Create SLO at the top-right of the table. When you create SLOs, you can see at a glance which of your services and operations are performing well and which are unhealthy. See service level objectives (SLOs) for more information. View top operation and dependency metrics Below the Services table, you can view top operations and dependencies across all services by call volume, faults, and latency. This set of graphs gives you critical information about which operations or dependencies may be unhealthy across all services. Choose any point in a graph to see a pop-up containing more detailed series information. Hover over the series descriptions at the bottom of a graph to see a pop-up containing detailed metrics for a specific operation or dependency path. Select the context menu button at the top-right corner of a graph to see additional options, including viewing CloudWatch metrics or logs pages. Monitor your application's operational health 1511 Amazon CloudWatch User Guide View detailed service activity and operational health with the service detail page When you instrument your application, Amazon CloudWatch Application Signals maps all of the services that your application discovers. Use the service detail page to see an overview of your services, operations, dependencies, canaries, and client requests for a single service. To view the service detail page, do the following: • Open the CloudWatch console. • Choose Services under the Application Signals section in the left navigation pane. • Choose the name of any service from the Services, Top services, or dependency tables. Under schedule-visits, you will see the account label and ID under the service name. The service detail page is organized into the following tabs: • Overview — Use this tab to see an overview of a single service, including the number of operations, dependencies, synthetics, and client pages. The tab shows key metrics for your entire service, top operations and dependencies. These metrics include time series data on latency, faults, and errors across all service operations for that service. • Service operations — Use this tab to see a list of the operations that your service calls and interactive graphs with key metrics that measure the health of each operation. You can select a data point in a graph to obtain information about traces, logs, or metrics associated with that data point. • Dependencies — Use this tab to see a list of dependencies that your service calls, and a list of metrics for those dependencies. • Synthetics canaries — Use this tab to see a list of synthetics canaries that simulate user calls to your service, and key performance metrics for how those canaries. • Client pages — Use this tab to see a list of client pages that call your service, and metrics that measure the quality of client interactions with your application. View your service overview Use the service overview page to view a high-level summary of metrics for all service operations in a single location. Check the performance of all the operations, dependencies, client pages and synthetics canaries that interact with your application. Use this information to help you determine where to focus efforts to identify issues, troubleshoot errors, and find opportunities for optimization. Monitor your application's operational health 1512 Amazon CloudWatch User Guide Choose any link in Service Details to view information that is related to a specific service. For example, for services hosted in Amazon EKS, the service details page shows Cluster, Namespace, and Workload information. For services hosted in Amazon ECS or Amazon EC2, the service details page shows the Environment value. Under Services, the Overview tab displays a summary of the following: • Operations – Use this tab to see the health of your service operations. The health status is determined by service level indicators (SLI) that are defined as a part of a service
acw-ug-406
acw-ug.pdf
406
1512 Amazon CloudWatch User Guide Choose any link in Service Details to view information that is related to a specific service. For example, for services hosted in Amazon EKS, the service details page shows Cluster, Namespace, and Workload information. For services hosted in Amazon ECS or Amazon EC2, the service details page shows the Environment value. Under Services, the Overview tab displays a summary of the following: • Operations – Use this tab to see the health of your service operations. The health status is determined by service level indicators (SLI) that are defined as a part of a service level objective (SLO). • Dependencies – Use this tab to see the top dependencies of the services called by your application, listed by fault rate and to see the health of your service dependencies. The health status is determined by service level indicators (SLI) that are defined as a part of a service level objective (SLO). • Synthetics canaries – Use this tab to see the result of simulated calls to endpoints or APIs associated with your service, and the number of failed canaries. • Client pages – Use this tab to see top pages called by clients that have asynchronous JavaScript and XML (AJAX) errors. The following illustration shows an overview of your services: The Overview tab also displays a graph of dependencies with the highest latency across all services. Use the p99, p90 and p50 latency metrics to quickly assess which dependencies are contributing to your total service latency, as follows: Monitor your application's operational health 1513 Amazon CloudWatch User Guide For example, the previous graph shows that 99% of the requests made to the customer-service dependency were completed in approximately 4,950 milliseconds. The other dependencies took less time. Graphs displaying the top four service operations by latency show the volume of requests, availability, fault rate, and error rate for those services, as shown in the following image: The Service details section displays the details of the service including the Account ID and Account label. View your service operations When you instrument your application, Application Signals discovers all of the service operations that your application calls. Use the Service operations tab to see a table that contains the service operations and a set of metrics that measure the performance of a selected operation. These metrics include SLI status, number of dependencies, latency, volume, faults, errors, and availability, as shown in the following image: Filter the table to make it easier to find a service operation by choosing one or more properties from the filter text box. As you choose each property, you are guided through filter criteria and will Monitor your application's operational health 1514 Amazon CloudWatch User Guide see the complete filter below the filter text box. Choose Clear filters at any time to remove the table filter. Choose the SLI status for an operation to display a popup containing a link to any unhealthy SLI, and a link to see all SLOs for the operation, as shown in the following table: The service operations table lists the SLI status, the number of healthy or unhealthy SLIs, and the total number of SLOs for each operation. Use SLIs to monitor latency, availability, and other operational metrics that measure the operational health of a service. Use an SLO to check the performance and health status of your services and operations. To create an SLO, do the following: • If an operation does not have an SLO, choose the Create SLO button within the SLI Status column. • If an operation already has an SLO, do the following: • Select the radio button next to the operation name. • Choose Create SLO from the Actions down arrow at the top right of the table. For more information, see service level objectives (SLOs). The Dependencies column shows the number of dependencies this operation calls. Choose this number to open the Dependencies tab filtered to the selected operation. View service operations metrics, correlated traces, and application logs Application Signals correlates service operation metrics with AWS X-Ray traces, CloudWatch Container Insights, and application logs. Use these metrics to troubleshoot operational health issues. To view metrics as graphical information, do the following: Monitor your application's operational health 1515 Amazon CloudWatch User Guide 1. Select a service operation in the Service operations table to see a set of graphs for the selected operation above the table with metrics for Volume and Availability, Latency, and Faults and Errors. 2. Hover over a point in a graph to view more information. 3. Select a point to open a diagnostic pane that shows correlated traces, metrics, and application logs for the selected point in the graph. The following image shows the tooltip that appears after hovering over a point in the graph, and the diagnostic pane which
acw-ug-407
acw-ug.pdf
407
your application's operational health 1515 Amazon CloudWatch User Guide 1. Select a service operation in the Service operations table to see a set of graphs for the selected operation above the table with metrics for Volume and Availability, Latency, and Faults and Errors. 2. Hover over a point in a graph to view more information. 3. Select a point to open a diagnostic pane that shows correlated traces, metrics, and application logs for the selected point in the graph. The following image shows the tooltip that appears after hovering over a point in the graph, and the diagnostic pane which appears after clicking on a point. The tooltip contains information about the associated data point in the Faults and Errors graph. The pane contains Correlated traces, Top contributors, and Application logs associated with the selected point. Correlated traces Look at related traces to understand an underlying issue with a trace. You can check to see if correlated traces or any service nodes associated with them behave similarly. To examine correlated traces, choose a Trace ID from the Correlated traces table to open the X-Ray trace details page for the chosen trace. The trace details page contains a map of service nodes that are associated with the selected trace and a timeline of trace segments. Top contributors View the top contributors to find main input sources to a metric. Group contributors by different components to look for similarities within the group and understand how trace behavior differs between them. Monitor your application's operational health 1516 Amazon CloudWatch User Guide The Top contributors tab gives metrics for Call volume, Availability, Avg latency, Errors, and Faults for each group. The following example image shows top contributors to a suite of metrics for an application deployed on an Amazon EKS platform: The top contributors contains the following metrics: • Call volume - Use the call volume to understand the number of requests per time interval for a group. • Availability - Use availability to see what percentage of time that no faults were detected for a group. • Avg latency - Use latency to check the average time that requests ran for a group over a time interval that depends on how long ago the requests that you are investigating were made. Requests that were made less than 15 days prior are evaluated over 1 minute intervals. Requests that were made between 15 and 30 days prior, inclusive, are evaluated over 5 minute intervals. For example, if you are investigating requests that caused a fault 15 days ago, the call volume metric is equal to the number of requests per 5 minute interval. • Errors - The number of errors per group measured over a time interval. • Faults - The number of faults per group over a time interval. Top contributors using Amazon EKS or Kubernetes Monitor your application's operational health 1517 Amazon CloudWatch User Guide Use information about the top contributors for applications deployed on Amazon EKS or Kubernetesto see operational health metrics grouped by Node, Pod and PodTemplateHash. The following definitions apply: • A pod is a group of one or more Docker containers that share storage and resources. A pod is the smallest unit that can be deployed on a Kubernetes platform. Group by pods to check if errors are related to pod-specific limitations. • A node is a server that runs pods. Group by nodes to check if errors are related to node-specific limitations. • A pod template hash is used to find a particular version of a deployment. Group by pod template hash to check if errors are related to a particular deployment. Top contributors using Amazon EC2 Use information about the top contributors for applications deployed on Amazon EKS to see operational health metrics grouped by instance ID, and auto scaling group. The following definitions apply: • An Instance ID is a unique identifier for the Amazon EC2 instance that your service runs. Group by instance ID to check if errors are related to a specific Amazon EC2 instance. • An auto scaling group is a collection of Amazon EC2 instances that allow you to scale up or down the resources you need to serve your application requests. Group by auto scaling group if you want to check if errors are limited in scope to the instances inside the group. Top contributors using a custom platform Use information about the top contributors for applications deployed using custom instrumentation to see operational health metrics grouped by Host name. The following definitions apply: • A host name identifies a device such as an endpoint or Amazon EC2 instance that is connected to a network. Group by host name to check if your errors are related to a specific physical or virtual device. View top contributors in Log Insights and
acw-ug-408
acw-ug.pdf
408
requests. Group by auto scaling group if you want to check if errors are limited in scope to the instances inside the group. Top contributors using a custom platform Use information about the top contributors for applications deployed using custom instrumentation to see operational health metrics grouped by Host name. The following definitions apply: • A host name identifies a device such as an endpoint or Amazon EC2 instance that is connected to a network. Group by host name to check if your errors are related to a specific physical or virtual device. View top contributors in Log Insights and Container Insights Monitor your application's operational health 1518 Amazon CloudWatch User Guide View and modify the automatic query that generated metrics for your top contributors in Log Insights. View infrastructure performance metrics by specific groups such as pods or nodes in Container Insights. You can sort clusters, nodes or workloads by resource consumption and quickly identify anomalies or and mitigate risks pro-actively before end user experience is impacted. An image showing how to select these options follows: In Container Insights, you can view metrics for your Amazon EKS or Amazon ECS container that are specific to the grouping of your top contributors. For example, if you grouped by pod for an EKS container to generate top contributors, container insights will show metrics and statistics filtered for your pod. In Log Insights, you can modify the query that generated the metrics under Top contributors using the following steps: 1. Select View in Log Insights. The Logs Insights page that opens contains an query that is automatically generated and contains the following information: • The log cluster group name. • The operation that you were investigating with CloudWatch. • The aggregate of the operational health metric interacted with on the graph. Monitor your application's operational health 1519 Amazon CloudWatch User Guide The log results are automatically filtered to show data from the last five minutes before you selected the data point on the service graph. 2. To edit the query, replace the generated text with your changes. You can also use the Query generator to help you generate a new query, or update the existing query. Application logs Use the query in the Application logs tab to generate logged information for your current log group, service and insert a timestamp. A log group is a group of log streams that you can define when you configure your application. Use a log group to organize logs with similar characteristics including the following: • Capture logs from a specific organization, source or function. • Capture logs that are accessed by a particular user. • Capture logs for a specific time period. Use these log streams to track specific groups or time frames. You can also set up monitoring rules, alarms and notifications for these log groups. For more information about log groups, see Working with log groups and log streams. The application logs query returns the logs, recurring text patterns and graphical visualizations for your log groups. To run the query, select Run query in Logs Insights to either run the automatically generated query or modify the query. To edit the query, replace the automatically generated text with your changes. You can also use the Query generator to help you generate a new query or update the existing query. The following image shows the sample query that is automatically generated based on the selected point in the service operations graph: Monitor your application's operational health 1520 Amazon CloudWatch User Guide In the preceding image, CloudWatch has automatically detected the log group that is associated with your selected point, and included it in a generated query. View your service dependencies Choose the Dependencies tab to display the Dependencies table and a set of metrics for the dependencies of all service operations or a single operation. The table contains a list of dependencies discovered by Application Signals, including metrics for SLI status, latency, call volume, fault rate, error rate, and availability. At the top of the page, choose an operation from the down arrow list to view its dependencies, or choose All to see dependencies for all operations. Monitor your application's operational health 1521 Amazon CloudWatch User Guide Filter the table to make it easier to find what you're looking for, by choosing one or more properties from the filter text box. As you choose each property, you are guided through filter criteria and will see the complete filter below the filter text box. Choose Clear filters at any time to remove the table filter. Select Group by Dependency at the top right of the table to group dependencies by service and operation name. When grouping is turned on, expand or collapse a group of dependencies with the + icon next to the dependency name. The
acw-ug-409
acw-ug.pdf
409
User Guide Filter the table to make it easier to find what you're looking for, by choosing one or more properties from the filter text box. As you choose each property, you are guided through filter criteria and will see the complete filter below the filter text box. Choose Clear filters at any time to remove the table filter. Select Group by Dependency at the top right of the table to group dependencies by service and operation name. When grouping is turned on, expand or collapse a group of dependencies with the + icon next to the dependency name. The Dependency column displays the dependency service name, while the Remote Operation column displays the service operation name. The SLI status column displays the number of healthy or unhealthy SLIs along with the total number of SLIs for each dependency. When calling AWS services, the Target column displays the AWS resource, such as DynamoDB table or Amazon SNS queue. To select a dependency, select the option next to a dependency in the Dependencies table. This shows a set of graphs that display detailed metrics for call volume, availability, faults, and errors. Hover over a point in a graph to see a popup containing more information. Select a point in a graph to open a diagnostic pane that shows correlated traces for the selected point in the graph. Choose a trace ID from the Correlated traces table to open the X-Ray Trace details page for the selected trace. Monitor your application's operational health 1522 Amazon CloudWatch View your Synthetics canaries User Guide Choose the Synthetics Canaries tab to display the Synthetics Canaries table, and a set of metrics for each canary in the table. The table includes metrics for success percentage, average duration, runs, and failure rate. Only canaries that are enabled for AWS X-Ray tracing are displayed. Use the filter text box in the synthetics canaries table to find the canary that you are interested in. Each filter that you create appears below the filter text box. Choose Clear filters at any time to remove the table filter. Select the radio button next to the name of the canary to see a set of tabs containing graphs detailed metrics including success percentage, errors and duration. Hover over a point in a graph to see a popup containing more information. Select a point in a graph to open a diagnostic pane that shows canary runs that correlate to the selected point. Select a canary run and choose the Run time to see artifacts for your selected canary run including logs, HTTP Archive (HAR) files, screenshots, and suggested steps to help you troubleshoot problems. Choose Larn more to open the CloudWatch Synthetics Canaries page next to Canary runs. View your client pages Choose the Client pages tab to display a list of client web pages that call your service. Use the set of metrics for the selected client page to measure the quality of your client's experience when interacting with a service or application. These metrics include page loads, web vitals, and errors. Monitor your application's operational health 1523 Amazon CloudWatch User Guide To display your client pages in the table, you must configure your CloudWatch RUM web client for X-Ray tracing and turn on Application Signals metrics for your client pages. Choose Manage pages to select which pages are enabled for Application Signals metrics. Use the filter text box to find the client page or application monitor that you are interested in below the filter text box. Choose Clear filters to remove the table filter. Select Group by Client to group client pages by client. When grouped, choose the + icon next to a client name to expand the row and see all pages for that client. To select a client page, select the option next to a client page in the Client pages table. You will see a set of graphs that display detailed metrics. Hover over a point in a graph to see a popup containing more information. Select a point in a graph to open a diagnostic pane that shows correlated performance navigation events for the selected point in the graph. Choose an event ID from the list of navigation events to open the CloudWatch RUM Page view for the chosen event. Note To see AJAX errors within your client pages, use the CloudWatch RUM web client version 1.15 or newer. Monitor your application's operational health 1524 Amazon CloudWatch User Guide Currently, up to 100 operations, canaries, and client pages, and up to 250 dependencies, can be shown per service. View your application topology and monitor operational health with the CloudWatch service map Note The CloudWatch service map replaces the ServiceLens map. To see a map of your application based on AWS X-Ray traces, open the X-Ray Trace Map.
acw-ug-410
acw-ug.pdf
410
navigation events to open the CloudWatch RUM Page view for the chosen event. Note To see AJAX errors within your client pages, use the CloudWatch RUM web client version 1.15 or newer. Monitor your application's operational health 1524 Amazon CloudWatch User Guide Currently, up to 100 operations, canaries, and client pages, and up to 250 dependencies, can be shown per service. View your application topology and monitor operational health with the CloudWatch service map Note The CloudWatch service map replaces the ServiceLens map. To see a map of your application based on AWS X-Ray traces, open the X-Ray Trace Map. Choose Trace Map under the X-Ray section in the left navigation pane of the CloudWatch console. Use the service map to view the topology of your application clients, synthetics canaries, services and dependencies, and monitor operational health. To view the service map, open the CloudWatch console and choose Service Map under the Application Signals section in the left navigation pane. After you enable your application for Application Signals, use the service map to make it easier to monitor your application's operational health: • View connections between client, canary, service, and dependency nodes to help you understand your application topology and execution flow. This is especially helpful if your service operators are not your development team. • See which services are meeting or not meeting your service level objectives (SLOs). When a service is not meeting your SLOs, you can quickly identify whether a downstream service or dependency might be contributing to the issue or impacting multiple upstream services. • Select an individual client, synthetics canary, service, or dependency node to see related metrics. The Service details page shows more detailed information about operations, dependencies, synthetics canaries, and client pages. • Filter and zoom the service map to make it easier to focus on a part of your application topology, or see the entire map. Create a filter by choosing one or more properties from the filter text box. As you choose each property, you are guided through filter criteria. You will see the complete filter below the filter text box. Choose Clear filters at any time to remove the filter. Monitor your application's operational health 1525 Amazon CloudWatch User Guide The following example service map shows services with edges connecting them to components that they interact with. If an SLO is defined, the service map also shows health status. Explore the service map After you have enabled your application for Application Signals, the service map displays nodes representing your services and their dependencies. Turn on active tracing for your CloudWatch RUM clients and synthetics canaries to see client and canary nodes on the map. By default, canaries, RUM clients, and AWS service dependencies of the same kind are grouped together into a single expandable icon in the service map. Service dependencies outside of AWS are not grouped together by default. For example, in the following image, all Amazon S3 buckets are grouped together under one expandable icon: Monitor your application's operational health 1526 Amazon CloudWatch User Guide In the previous image, the label between the Amazon S3 grouping and originating service displays the number of edges to the group in parenthesis under the dependency's icon. Select the (+) icon to expand the group and see its individual elements, as shown in the following image: Monitor your application's operational health 1527 Amazon CloudWatch User Guide Choose a tab for information about exploring each kind of node and the edges (connections) between them. View your application services You can view your application services and the status of their SLOs and service level indicators (SLIs) in the Service Map. If you didn't create SLOs for a service, choose the Create SLO button below the service node. The Service Map displays all of your services. It also shows the customers and canaries that consume the service and the dependencies that your services calls, as shown in the following image: Monitor your application's operational health 1528 Amazon CloudWatch User Guide The following icons represent examples of application services in the service map: • Amazon Elastic Kubernetes Service: • A Kubernetes container: Monitor your application's operational health 1529 Amazon CloudWatch User Guide • Amazon Elastic Compute Cloud (Amazon EC2): Monitor your application's operational health 1530 Amazon CloudWatch User Guide • Other application service types not previously listed: Monitor your application's operational health 1531 Amazon CloudWatch User Guide When you select a service node, a pane opens displaying detailed service information: • Metrics for call volume, latency, error, and fault rate. • The number of SLIs and SLOs that are healthy or unhealthy. • The option to view more information about an SLO. • The number of service operations, dependencies, synthetics canaries, and client pages. • The option to select each number to open the Service details
acw-ug-411
acw-ug.pdf
411
Cloud (Amazon EC2): Monitor your application's operational health 1530 Amazon CloudWatch User Guide • Other application service types not previously listed: Monitor your application's operational health 1531 Amazon CloudWatch User Guide When you select a service node, a pane opens displaying detailed service information: • Metrics for call volume, latency, error, and fault rate. • The number of SLIs and SLOs that are healthy or unhealthy. • The option to view more information about an SLO. • The number of service operations, dependencies, synthetics canaries, and client pages. • The option to select each number to open the Service details page for it. • The application name, if you have associated the underlying compute resource with an application using AppRegistry or the Applications card on the AWS Management Console home page. Monitor your application's operational health 1532 Amazon CloudWatch User Guide • Choose the application name to display the application details in the myApplications console page. • The Cluster, Namespace, and Workload for services hosted in Amazon EKS, or Environment for services hosted in Amazon ECS or Amazon EC2. For Amazon EKS-hosted services, choose any link to open CloudWatch Container Insights. Select an edge or connection between a service node and a downstream service or dependency node. This opens a pane containing top paths by fault rate, latency, and error rate, as shown in the following example image. Choose any link in the pane to open the Service details page and see detailed information for the chosen service or dependency. View dependencies Your application dependencies are displayed on the service map, connected to the services that call them. Choose a dependency node to open a pane containing top paths by fault rate, latency, and error rate. Choose any service or target link to open the Service Details page and see detailed Monitor your application's operational health 1533 Amazon CloudWatch User Guide information about the chosen service or dependency target, as shown in the example image below: You can view the dependencies and the status of SLOs created on the dependencies. Service dependencies are grouped together by default into a single expandable icon. Select the (+) icon, as shown in the previous image, to expand the group and see its individual elements. The following icons represent examples of dependency nodes in the service map: • An Amazon S3 bucket: Monitor your application's operational health 1534 Amazon CloudWatch User Guide • An Amazon Kinesis stream: Monitor your application's operational health 1535 Amazon CloudWatch User Guide • Amazon Simple Queue Service (Amazon SQS): Monitor your application's operational health 1536 Amazon CloudWatch User Guide • An Amazon DynamoDB table: Monitor your application's operational health 1537 Amazon CloudWatch User Guide • An Amazon Bedrock model: Monitor your application's operational health 1538 Amazon CloudWatch User Guide • Other dependency types not previously listed: Monitor your application's operational health 1539 Amazon CloudWatch User Guide View clients After you turn on X-Ray tracing for your CloudWatch RUM web clients, they display on the service map connected to services they call. Choose a client node to open a pane displaying detailed client information: • Metrics for page loads, average load time, errors, and average web vitals. • A graph displaying a breakdown of errors. • A link to display the client details in CloudWatch RUM. Monitor your application's operational health 1540 Amazon CloudWatch User Guide RUM clients are grouped together by default into a single expandable icon. Select the (+) icon, as shown in the following image, to expand the group and see its individual elements. The following icon represents an example of a RUM client in the service map: • A RUM client – Monitor your application's operational health 1541 Amazon CloudWatch User Guide Note To see AJAX errors within your client pages, use the CloudWatch RUM web client version 1.15 or newer. View synthetics canaries After you turn on AWS X-Ray tracing for your CloudWatch Synthetics canaries, they display on the service map connected to services they call, as shown in the following example image: Choose a canary node to open a pane displaying detailed canary information, as shown in the following image: Monitor your application's operational health 1542 Amazon CloudWatch User Guide Canaries are grouped together by default into a single expandable icon. Select the (+) icon, as shown in the previous image, to expand the group and see its individual elements. The following icons represent examples of clients in the service map: • A synthetics canary – Monitor your application's operational health 1543 Amazon CloudWatch User Guide Monitor your application's operational health 1544 Amazon CloudWatch User Guide In the pane for canary nodes, you can see the following: • Metrics for success percentage, average duration, and errors. • The status of the last canary run. • A graph displaying canary run duration. Hover over a
acw-ug-412
acw-ug.pdf
412
by default into a single expandable icon. Select the (+) icon, as shown in the previous image, to expand the group and see its individual elements. The following icons represent examples of clients in the service map: • A synthetics canary – Monitor your application's operational health 1543 Amazon CloudWatch User Guide Monitor your application's operational health 1544 Amazon CloudWatch User Guide In the pane for canary nodes, you can see the following: • Metrics for success percentage, average duration, and errors. • The status of the last canary run. • A graph displaying canary run duration. Hover over a graph series to see a pop-up containing more information. • A link to display canary details in CloudWatch Synthetics. Example: Use Application Signals to resolve an operational health issue The following scenario provides an example of how Application Signals can be used to monitor your services and identify service quality issues. Drill down to identify potential root causes and take action to resolve the issue. This example is focused on a pet clinic application composed of several microservices that call AWS services such as DynamoDB. Monitor your application's operational health 1545 Amazon CloudWatch User Guide Jane is part of a DevOps team that oversees the operational health of a pet clinic application. Jane's team is committed to ensuring that the application is highly available and responsive. They use service level objectives (SLOs) to measure application performance against these business commitments. She receives an alert about several unhealthy service level indicators (SLIs). She opens the CloudWatch console and navigates to the Services page, where she sees several services in an unhealthy state. At the top of the page, Jane sees that the visits-service is the top service by fault rate. She selects the link in the graph, which opens the Service detail page for the service. She sees that there is an unhealthy operation in the Service operations table. She selects this operation and sees in the Volume and Availability graph that there are periodic call volume spikes that seem to correlate to dips in availability. Monitor your application's operational health 1546 Amazon CloudWatch User Guide In order to look closer at the dips in service availability, Jane selects one of the availability data points in the graph. A drawer opens showing X-Ray traces that are correlated to the selected data point. She sees that there are multiple traces containing faults. Monitor your application's operational health 1547 Amazon CloudWatch User Guide Jane selects one of the correlated traces with a fault status, which opens the X-Ray Trace detail page for the selected trace. Jane scrolls down to the Segments Timeline section and follows the call path until she sees that calls to a DynamoDB table are returning errors. She selects the DynamoDB segment and navigates to the Exceptions tab of the right-side drawer. Jane sees that a DynamoDB resource is misconfigured, resulting in errors during spikes in customer requests. The DynamoDB table's level of provisioned throughput is periodically exceeded, resulting in service availability issues and unhealthy SLIs. Based on this information, her team is able to configure a higher level of provisioned throughput and ensure high availability of the application. Monitor your application's operational health 1548 Amazon CloudWatch User Guide Example: Use Application Signals to troubleshoot generative AI applications interacting with Amazon Bedrock models You can use Application Signals to troubleshoot your generative AI applications that interact with Amazon Bedrock models. Application Signals streamlines this process by providing out-of-the-box telemetry data, offering deeper insights into your application's interactions with LLM models. It helps address key use cases such as: • Model configuration issues • Model usage costs • Model latency • Model response generation stopped reasons Enabling Application Signals with LLM/GenAI Observability provides real-time visibility into your application's interactions with Amazon Bedrock services. Application Signals automatically generates and correlates performance metrics and traces for Amazon Bedrock API calls. Application Signals currently support the following LLM Models from Amazon Bedrock. • AI21 Jamba • Amazon Titan • Anthropic Claude • Cohere Command • Meta Llama • Mistral AI • Nova Fine-grained metrics and traces For each Amazon Bedrock API call, Application Signals generates detailed performance metrics at the resource level, including: • Model ID • Guardrails ID • Knowledge Base ID Monitor your application's operational health 1549 Amazon CloudWatch • Bedrock Agent ID User Guide Additionally, correlated trace spans at the same level help provide a comprehensive view of request execution and dependencies. OpenTelemetry GenAI attributes support Application Signals generates the following GenAI attributes for Amazon Bedrock API calls with OpenTelemetry semantic convention. These attributes help analyze model usage, cost, and response quality, and can be leveraged through Transaction Search for deeper insights. • gen_ai.system • gen_ai.request.model • gen_ai.request.max_tokens • gen_ai.request.temperature • gen_ai.request.top_p • gen_ai.usage.input_tokens • gen_ai.usage.output_tokens • gen_ai.response.finish_reasons Monitor your application's
acw-ug-413
acw-ug.pdf
413
Model ID • Guardrails ID • Knowledge Base ID Monitor your application's operational health 1549 Amazon CloudWatch • Bedrock Agent ID User Guide Additionally, correlated trace spans at the same level help provide a comprehensive view of request execution and dependencies. OpenTelemetry GenAI attributes support Application Signals generates the following GenAI attributes for Amazon Bedrock API calls with OpenTelemetry semantic convention. These attributes help analyze model usage, cost, and response quality, and can be leveraged through Transaction Search for deeper insights. • gen_ai.system • gen_ai.request.model • gen_ai.request.max_tokens • gen_ai.request.temperature • gen_ai.request.top_p • gen_ai.usage.input_tokens • gen_ai.usage.output_tokens • gen_ai.response.finish_reasons Monitor your application's operational health 1550 Amazon CloudWatch User Guide For example, your can leverage the analytic capability from Transaction Search to compare the token usage and cost across different LLM models for the same prompt, enabling cost-efficient model selection. For more information, see Improve Amazon Bedrock Observability with CloudWatch Application Signals. Monitor your application's operational health 1551 Amazon CloudWatch User Guide Metrics collected by Application Signals Application Signals collects both standard application metrics and runtime metrics from the applications that you enable it for. Standard application metrics relate to the most critical parts of service performance, latency and availability. Runtime metrics track application metrics over time, including memory usage, CPU usage, and garbage collection. Application Signals displays the runtime metrics in the context of the services that you have enabled for Application Signals. When you have an operational issue, observing the runtime metrics can be useful to help you find the root cause of the issue. For example, you can see if spikes in latency in your service relate to spikes in a runtime metric. Topics • Standard application metrics collected • Runtime metrics • Disabling the collection of runtime metrics Standard application metrics collected Application Signals collects standard application metrics from the services that it discovers. These metrics relate to the most critical aspects of a service's performance: latency, faults, and errors. They can help you identify issues, monitor performance trends, and optimize resources to improve the overall user experience. The following table lists the metrics collected by Application Signals. These metrics are sent to CloudWatch in the ApplicationSignals namespace. Metric Latency Fault Description The delay before data transfer begins after the request is made. Units: Milliseconds A count of both HTTP 5XX server-side faults and OpenTelemetry span status errors. Metrics collected by Application Signals 1552 Amazon CloudWatch User Guide Metric Error Description Units: None A count of HTTP 4XX client-side errors. These are considered to be request errors that are not caused by service problems. Therefore, the Availability metric displayed on Application Signals dashboards does not regard these errors as service faults. Units: None The Availability metric displayed on Application Signals dashboards is computed as (1 - Faults/Total)*100. Total responses includes all responses and is derived from SampleCount(Latency). Successful responses are all responses without a 5XX error. 4XX responses are treated as successful when Application Signals calculates Availability. Dimensions collected and dimension combinations The following dimensions are defined for each of the standard application metrics. For more information about dimensions, see Dimensions. Different dimensions are collected for service metrics and dependency metrics. Within the services discovered by Application Signals, when microservice A calls microservice B, microservice B is serving the request. In this case, microservice A emits dependency metrics and microservice B emits service metrics. When a client calls microservice A, microservice A is serving the request and emits service metrics. Dimensions for service metrics The following dimensions are collected for service metrics. Dimension Description Service The name of the service. The maximum value is 255 characters. Operation The name of the API operation or other activity. Metrics collected by Application Signals 1553 Amazon CloudWatch User Guide Dimension Description The maxiumum value is 1024 characters. Currently, you can set service level objectives on operations only if the operation name is 194 characters or fewer. Environment The name of the environment where services are running. If services are not running on Amazon EKS, you can specify an optional custom value for deployment.environment in the OTEL_ATTR IBUTE_RESOURCES parameter. The maxiumum value is 259 characters. When you view these metrics in the CloudWatch console, you can view them using the following dimension combinations: • [Environment, Service, Operation, [Latency, Error, Fault]] • [Environment, Service, [Latency, Error, Fault]] Dimensions for dependency metrics The following dimensions are collected for dependency metrics: Dimension Description Service The name of the service. The maximum value is 255 characters. Operation The name of the API operation or other operation. The maximum value is 1024 characters. RemoteService The name of the remote service being invoked. The maximum value is 255 characters. RemoteOperation The name of the API operation being invoked. Metrics collected by Application Signals 1554 Amazon CloudWatch User Guide Dimension Description The maximum value is 1024 characters. Environment The name
acw-ug-414
acw-ug.pdf
414
• [Environment, Service, Operation, [Latency, Error, Fault]] • [Environment, Service, [Latency, Error, Fault]] Dimensions for dependency metrics The following dimensions are collected for dependency metrics: Dimension Description Service The name of the service. The maximum value is 255 characters. Operation The name of the API operation or other operation. The maximum value is 1024 characters. RemoteService The name of the remote service being invoked. The maximum value is 255 characters. RemoteOperation The name of the API operation being invoked. Metrics collected by Application Signals 1554 Amazon CloudWatch User Guide Dimension Description The maximum value is 1024 characters. Environment The name of the environment where services are running. If services are not running on Amazon EKS, you can specify an optional custom value for deployment.environment in the OTEL_ATTR RemoteEnv ironment IBUTE_RESOURCES parameter. The maxiumum value is 259 characters. The name of the environment where dependency services are running. The RemoteEnvironment parameter is automatically generated when a service calls a dependency and they are both running in the same cluster. Otherwise, RemoteEnvironment is neither generated nor reported in the service dependency's metrics. Currently only available on Amazon EKS and K8S platforms. The maximum value is 259 characters. RemoteRes ourceIden tifier The name of the resource invoked by a remote call. The RemoteRes parameter is automatically generated if service ourceIdentifier calls a remote AWS service. Otherwise, RemoteResourceIden tifier is neither generated nor reported in the service dependency's metrics. The maximum value is 1024 characters. RemoteRes ourceType The type of the resource that is invoked by a remote call. Required only if RemoteResourceIdentifier is defined. The maximum value is 1024 characters. When you view these metrics in the CloudWatch console, you can view them using the following dimension combinations: Running on Amazon EKS clusters Metrics collected by Application Signals 1555 Amazon CloudWatch User Guide • [Environment, Service, Operation, RemoteService, RemoteOperation, RemoteEnvironment, RemoteResourceIdentifier, RemoteResourceType, [Latency, Error, Fault]] • [Environment, Service, Operation, RemoteService, RemoteOperation, RemoteEnvironment, [Latency, Error, Fault]] • [Environment, Service, Operation, RemoteService, RemoteOperation, RemoteResourceIdentifier, RemoteResourceType, [Latency, Error, Fault]] • [Environment, Service, Operation, RemoteService, RemoteOperation, [Latency, Error, Fault]] • [Environment, Service, RemoteService, RemoteEnvironment, [Latency, Error, Fault]] • [Environment, Service, RemoteService, [Latency, Error, Fault]] • [Environment, Service, RemoteService, RemoteOperation, RemoteEnvironment, RemoteResourceIdentifier, RemoteResourceType, [Latency, Error, Fault]] • [Environment, Service, RemoteService, RemoteOperation, RemoteEnvironment, [Latency, Error, Fault]] • [Environment, Service, RemoteService, RemoteOperation, RemoteResourceIdentifier, RemoteResourceType, [Latency, Error, Fault]] • [Environment, Service, RemoteService, RemoteOperation, [Latency, Error, Fault]] • [RemoteService [Latency, Error, Fault]] • [RemoteService, RemoteResourceIdentifier, RemoteResourceType [Latency, Error, Fault]] Runtime metrics Application Signals uses the AWS Distro for OpenTelemetry SDK to automatically collect OpenTelemetry-compatible metrics from your Java and Python applications. To have runtime metrics collected, you must meet the following pre-requisites: • Your CloudWatch agent must be version 1.300049.1 or later. • If you use the Amazon CloudWatch Observability EKS add-on, it must be version 2.30- eksbuild.1 or later. If you update the add-on, you must restart your applications. Metrics collected by Application Signals 1556 Amazon CloudWatch User Guide • For Java applications, you must be running 1.32.5 or later of the AWS Distro for OpenTelemetry SDK for Java. • For Python applications, you must be running 0.7.0 or later of the AWS Distro for OpenTelemetry SDK for Python. • For .Net applications, you must be running 1.6.0 or later of the AWS Distro for OpenTelemetry SDK for .Net. Runtime metrics are not collected for Node.js applications. Runtime metric are charged as part of Application Signals costs. For more information about CloudWatch pricing, see Amazon CloudWatch Pricing. Note Known issues The runtime metrics collection in the Java SDK release v1.32.5 is known to not work with applications using JBoss Wildfly. This issue extends to the Amazon CloudWatch Observability EKS add-on, affecting versions 2.3.0-eksbuild.1 through 2.6.0- eksbuild.1. The issue is fixed in Java SDK release v1.32.6 and the Amazon CloudWatch Observability EKS add-on version v3.0.0-eksbuild.1. If you are impacted, either upgrade the Java SDK version or disable your runtime metrics collection by adding the environment variable OTEL_AWS_APPLICATION_SIGNALS_RUNTIME_ENABLED=false to your application. Java runtime metrics Application Signals collects the following JVM metrics from Java applications that you enable for Application Signals. All runtime metrics are sent to CloudWatch in the ApplicationSignals namespace, and are collected with the Service and Environment dimension set. Metric name Description JVMGCDuration Aggregated metric for the duration of JVM garbage collection actions. Meaningful statistics Sum, Average, Minimum, Maximum Metrics collected by Application Signals 1557 Amazon CloudWatch Metric name Description Unit: Milliseconds User Guide Meaningful statistics JVMGCOldGenDuration Aggregated metric for the duration of JVM garbage collection actions of the old Sum, Average, Minimum, generation. Available only in G1. Maximum Unit: Milliseconds JVMGCYoungGenDuration Aggregated metric for the duration of JVM garbage collection actions of the Sum, Average, Minimum, young generation. Available only in G1. Maximum Unit: Milliseconds JVMGCCount Aggregated metric for the number of JVM garbage collection actions. Sum, Average, Minimum, JVMGCOldGenCount
acw-ug-415
acw-ug.pdf
415
Description JVMGCDuration Aggregated metric for the duration of JVM garbage collection actions. Meaningful statistics Sum, Average, Minimum, Maximum Metrics collected by Application Signals 1557 Amazon CloudWatch Metric name Description Unit: Milliseconds User Guide Meaningful statistics JVMGCOldGenDuration Aggregated metric for the duration of JVM garbage collection actions of the old Sum, Average, Minimum, generation. Available only in G1. Maximum Unit: Milliseconds JVMGCYoungGenDuration Aggregated metric for the duration of JVM garbage collection actions of the Sum, Average, Minimum, young generation. Available only in G1. Maximum Unit: Milliseconds JVMGCCount Aggregated metric for the number of JVM garbage collection actions. Sum, Average, Minimum, JVMGCOldGenCount Unit: None Maximum Aggregated metric for the number of JVM garbage collection actions of the old Sum, Average, Minimum, generation. Available only in G1. Maximum Unit: None JVMGCYoungGenCount Aggregated metric for the number of JVM garbage collection actions of the young generation. Available only in G1. Sum, Average, Minimum, Maximum Unit: None JVMMemoryHeapUsed The amount of memory heap used. Unit: Bytes Average, Minimum, Maximum Metrics collected by Application Signals 1558 Amazon CloudWatch User Guide Metric name Description JVMMemoryUsedAfter LastGC Amount of memory used, as measured after the most recent garbage collection event on this pool. Unit: Bytes JVMMemoryOldGenUsed The amount of memory used by the old generation. Unit: Bytes JVMMemorySurvivorS paceUsed The amount of memory heap used by the survivor space. Unit: Bytes JVMMemoryEdenSpaceUsed The amount of memory used by the eden space. Unit: Bytes JVMMemoryNonHeapUsed The amount of non-heap memory used. Unit: Bytes Meaningful statistics Average, Minimum, Maximum Average, Minimum, Maximum Average, Minimum, Maximum Average, Minimum, Maximum Average, Minimum, Maximum JVMThreadCount The number of executing threads, including both daemon and non-daemon threads. Sum, Average, Minimum, Maximum Unit: None JVMClassLoaded The number of classes loaded. Unit: None Sum, Average, Minimum, Maximum Metrics collected by Application Signals 1559 Amazon CloudWatch Metric name Description JVMCpuTime The CPU time used by the process, as reported by the JVM. Unit: None (Nanoseconds) JVMCpuRecentUtilization The recent CPU utilized by the process, as reported by the JVM. Unit: None User Guide Meaningful statistics Sum, Average, Minimum, Maximum Average, Minimum, Maximum Python runtime metrics Application Signals collects the following metrics from Python applications that you enable for Application Signals. All runtime metrics are sent to CloudWatch in the ApplicationSignals namespace, and are collected with the Service and Environment dimension set. Metric name Description PythonProcessGCCount The total number of objects currently being tracked. Unit: None PythonProcessGCGen 0Count The number of objects currently being tracked in Generation 0. Unit: None PythonProcessGCGen 1Count The number of objects currently being tracked in Generation 1. Unit: None Meaningful statistics Sum, Average, Minimum, Maximum Sum, Average, Minimum, Maximum Sum, Average, Minimum, Maximum Metrics collected by Application Signals 1560 Amazon CloudWatch Metric name Description PythonProcessGCGen 2Count The number of objects currently being tracked in Generation 2. Unit: None PythonProcessVMSMe moryUsed The total amount of virtual memory used by the process. Unit: Bytes PythonProcessRSSMe moryUsed The total amount of non-swapped physical memory used by the process. Unit: Bytes User Guide Meaningful statistics Sum, Average, Minimum, Maximum Average, Minimum, Maximum Average, Minimum, Maximum PythonProcessThrea dCount The number of threads currently used by the process. Sum, Average, Minimum, Unit: None PythonProcessCpuTime The CPU time used by the process. Unit: Seconds PythonProcessCpuUt The CPU utilization of the process. ilization Unit: None Maximum Sum, Average, Minimum, Maximum Average, Minimum, Maximum .Net runtime metrics Application Signals collects the following metrics from .Net applications that you enable for Application Signals. All runtime metrics are sent to CloudWatch in the ApplicationSignals namespace, and are collected with the Service and Environment dimension set. Metrics collected by Application Signals 1561 Amazon CloudWatch User Guide Metric name Description Meaningful statistics DotNetGCGen0Count The total number of garbage collection metrics tracked in Generation 0 since the Sum, Average, Minimum, process started. Unit: None Maximum DotNetGCGen1Count The total number of garbage collection metrics tracked in Generation 1 since the Sum, Average, Minimum, process started. Unit: None Maximum DotNetGCGen2Count The total number of garbage collection metrics tracked in Generation 2 since the Sum, Average, Minimum, process started. Unit: None DotNetGCDuration The total amount of time paused in garbage collection since the process started. Unit: None Maximum Sum, Average, Minimum, Maximum DotNetGCGen0HeapSize The heap size (including fragmentation) of Generation 0 observed during the latest garbage collection. Average, Minimum, Maximum Note This metric is only available after the first Garbage Collection is complete. Unit: Bytes Metrics collected by Application Signals 1562 Amazon CloudWatch User Guide Metric name Description DotNetGCGen1HeapSize The heap size (including fragmentation) of Generation 1 observed during the latest garbage collection. Meaningful statistics Average, Minimum, Maximum Note This metric is only available after the first Garbage Collection is complete. Unit: Bytes DotNetGCGen2HeapSize The heap size (including fragmentation) of Generation 2 observed during the latest garbage collection. Average, Minimum, Maximum Note This metric is only available after the first Garbage
acw-ug-416
acw-ug.pdf
416
observed during the latest garbage collection. Average, Minimum, Maximum Note This metric is only available after the first Garbage Collection is complete. Unit: Bytes Metrics collected by Application Signals 1562 Amazon CloudWatch User Guide Metric name Description DotNetGCGen1HeapSize The heap size (including fragmentation) of Generation 1 observed during the latest garbage collection. Meaningful statistics Average, Minimum, Maximum Note This metric is only available after the first Garbage Collection is complete. Unit: Bytes DotNetGCGen2HeapSize The heap size (including fragmentation) of Generation 2 observed during the latest garbage collection. Average, Minimum, Maximum Note This metric is only available after the first Garbage Collection is complete. Unit: Bytes Metrics collected by Application Signals 1563 Amazon CloudWatch Metric name Description User Guide Meaningful statistics DotNetGCLOHHeapSize The large object heap size (including fragmentation) observed during the latest Average, Minimum, garbage collection. Maximum Note This metric is only available after the first Garbage Collection is complete. Unit: Bytes DotNetGCPOHHeapSize The pinned object heap size (including fragmentation) observed during the latest Average, Minimum, garbage collection. Maximum Note This metric is only available after the first Garbage Collection is complete. Unit: Bytes DotNetThreadCount The number of thread pool threads that currently exist. Unit: None Average, Minimum, Maximum Metrics collected by Application Signals 1564 Amazon CloudWatch User Guide Metric name Description DotNetThreadQueueLength The number of work items that are currently queued to be processed by the thread pool. Unit: None Meaningful statistics Average, Minimum, Maximum Disabling the collection of runtime metrics Runtime metrics are collected by default for Java and Python applications that are enabled for Application Signals. If you want to disable the collection of these metrics, follow the instructions in this section for your environment. Amazon EKS To disable runtime metrics in Amazon EKS applications at the application level, add the following environment variable to your workload specification. env: - name: OTEL_AWS_APPLICATION_SIGNALS_RUNTIME_ENABLED value: "false" To disable runtime metrics in Amazon EKS applications at the cluster level, apply the configuration to the advanced configuration of your Amazon CloudWatch Observability EKS add-on. { "agent": { "config": { "traces": { "traces_collected": { "application_signals": { } } }, "logs": { "metrics_collected": { "application_signals": { Metrics collected by Application Signals 1565 Amazon CloudWatch User Guide } } } }, "manager": { "autoInstrumentationConfiguration": { "java": { "runtime_metrics": { "enabled": false } }, "python": { "runtime_metrics": { "enabled": false } }, "dotnet": { "runtime_metrics": { "enabled": false } } } } } } Amazon ECS To disable runtime metrics in Amazon ECS applications, add the environment variable OTEL_AWS_APPLICATION_SIGNALS_RUNTIME_ENABLED=false in the new task definition revision and redeploy the application. EC2 To disable runtime metrics in Amazon EC2 applications, add the environment variable OTEL_AWS_APPLICATION_SIGNALS_RUNTIME_ENABLED=false before the application starts. Kubernetes To disable runtime metrics in Kubernetes applications at the application level, add the following environment variable to your workload specification. Metrics collected by Application Signals 1566 Amazon CloudWatch User Guide env: - name: OTEL_AWS_APPLICATION_SIGNALS_RUNTIME_ENABLED value: "false" To disable runtime metrics in Kubernetes applications at the cluster level, use the following: helm upgrade ... \ --set-string manager.autoInstrumentationConfiguration.java.runtime_metrics.enabled=false \ --set-string manager.autoInstrumentationConfiguration.python.runtime_metrics.enabled=false \ -\-set-string manager.autoInstrumentationConfiguration.dotnet.runtime_metrics.enabled=false Service level objectives (SLOs) You can use Application Signals to create service level objectives for the services for your critical business operations or dependencies. By creating SLOs on these services, you will be able to track them on the SLO dashboard, giving you an at-a-glance view of your most important operations. In addition to creating a quick view your operators can use to see the current status of critical operations, you can use SLOs to track the longer-term performance of your services, to ensure that they are meeting your expectations. If you have service level agreements with customers, SLOs are a great tool to ensure that they are met. Assessing your services' health with SLOs starts with setting clear, measurable objectives based on key performance metrics— service level indicators (SLIs). An SLO tracks the SLI performance against the threshold and goal that you set, and reports how far or how close your application performance is to the threshold. Application Signals helps you set SLOs on your key performance metrics. Application Signals automatically collects Latency and Availability metrics for every service and operation that it discovers, and these metrics are often ideal to use as SLIs. With the SLO creation wizard, you can use these metrics for your SLOs. You can then track the status of all of your SLOs with the Application Signals dashboards. You can set SLOs on specific operations or dependencies that your service calls or uses. You can use any CloudWatch metric or metric expression as an SLI, in addition to using the Latency and Availability metrics. Service level objectives (SLOs) 1567 Amazon CloudWatch User Guide Creating SLOs is very important for getting the most benefit from CloudWatch Application Signals. After you create SLOs, you can view their status in the Application
acw-ug-417
acw-ug.pdf
417
With the SLO creation wizard, you can use these metrics for your SLOs. You can then track the status of all of your SLOs with the Application Signals dashboards. You can set SLOs on specific operations or dependencies that your service calls or uses. You can use any CloudWatch metric or metric expression as an SLI, in addition to using the Latency and Availability metrics. Service level objectives (SLOs) 1567 Amazon CloudWatch User Guide Creating SLOs is very important for getting the most benefit from CloudWatch Application Signals. After you create SLOs, you can view their status in the Application Signals console to quickly see which of your these critical services and operations are performing well and which are unhealthy. Having SLOs to track provides the following major benefits: • It is easier for your service operators to see the current operational health of critical services as measured against the SLI. Then they can quickly triage and identify unhealthy services and operations. • You can track your service performance against measurable business goals over longer periods of time. By choosing what to set SLOs on, you are prioritizing what is important to you. The Application Signals dashboards automatically present information about what you have prioritized. When you create an SLO, you can also choose to create CloudWatch alarms at the same time to monitor the SLOs. You can set alarms that monitor for breaches of the threshold, and also for warning levels. These alarms can automatically notify you if the SLO metrics are breaching the threshold that you set, or if they are nearing a warning threshold. For example, an SLO nearing its warning threshold can let you know that your team might need to slow down churn in the application to make sure that long-term performance goals are met. Topics • SLO concepts • Calculate error budget and attainment for period-based SLOs • Calculate error budget and attainment for request-based SLOs • Calculate burn rates and optionally set burn rate alarms • Create an SLO • View and triage SLO status • Edit an existing SLO • Delete an SLO SLO concepts An SLO includes the following components: SLO concepts 1568 Amazon CloudWatch User Guide • A service level indicator (SLI), which is a key performance metric that you specify. It represents the desired level of performance for your application. Application Signals automatically collects the key metrics Latency and Availability for the services and operations that it discovers, and these can often be ideal metrics to set SLOs for. You choose the threshold to use for your SLI. For example, 200ms for latency. • A goal or attainment goal, which is the percentage of time or requests that the SLI is expected to meet the threshold over each time interval. The time intervals can be as short as hours or as long as a year. Intervals can be either calendar intervals or rolling intervals. • Calendar intervals are aligned with the calendar, such as an SLO that is tracked per month. CloudWatch automatically adjusts health, budget, and attainment numbers based on the number of days in a month. Calendar intervals are better suited for business goals that are measured on a calendar-aligned basis. • Rolling intervals are calculated on a rolling basis. Rolling intervals are better suited for tracking recent user experience of your application. • The period is a shorter length of time, and many periods make up an interval. The application's performance is compared to the SLI during each period within the interval. For each period, the application is determined to have either achieved or not achieved the necessary performance. For example, a goal of 99% with a calendar interval of one day and a period of 1 minute means that the application must meet or achieve the success threshold during 99% of the 1-minute periods during the day. If it does, then the SLO is met for that day. The next day is a new evaluation interval, and the application must meet or achieve the success threshold during 99% of the 1- minute periods during the second day to meet the SLO for that second day. An SLI can be based on one of the new standard application metrics collected by Application Signals. Alternatively, it can be any CloudWatch metric or metric expression. The standard application metrics that you can use for an SLI are Latency and Availability. Availability represents the successful responses divided by the total requests. It is calculated as (1 - Fault Rate)*100, where Fault responses are 5xx errors. Success responses are responses without a 5XX error. 4XX responses are treated as successful. SLO concepts 1569 Amazon CloudWatch User Guide Calculate error budget and attainment for period-based SLOs When you view information about an SLO, you see its current health status and its
acw-ug-418
acw-ug.pdf
418
standard application metrics collected by Application Signals. Alternatively, it can be any CloudWatch metric or metric expression. The standard application metrics that you can use for an SLI are Latency and Availability. Availability represents the successful responses divided by the total requests. It is calculated as (1 - Fault Rate)*100, where Fault responses are 5xx errors. Success responses are responses without a 5XX error. 4XX responses are treated as successful. SLO concepts 1569 Amazon CloudWatch User Guide Calculate error budget and attainment for period-based SLOs When you view information about an SLO, you see its current health status and its error budget. The error budget is the amount of time within the interval that can breach the threshold but still let the SLO be met. The total error budget is the total amount of breaching time that can be tolerated through the entire interval. The remaining error budget is the remaining amount of breaching time that can be tolerated during the current interval. This is after the amount of breaching time that has already happened has been subtracted from the total error budget. The following figure illustrates the attainment and error budget concepts for a goal with a 30-day interval, 1-minute periods, and a 99% attainment goal. 30 days includes 43,200 1-minute periods. 99% of 43,200 is 42,768, so 42,768 minutes during the month must be healthy for the SLO to be met. So far in the current interval, 130 of the 1-minute periods were unhealthy. Determine success within each period Within each period, the SLI data is aggregated into a single data point based on the statistic used for the SLI. This data point represents the entire length of the period. That single data point is compared to the SLI threshold to determine if the period is healthy. Seeing unhealthy periods Calculate error budget and attainment for period-based SLOs 1570 Amazon CloudWatch User Guide during the current time range on the dashboard can alert your service operators that the service needs to be triaged. If the period is determined to be unhealthy, the entire length of the period is counted as failed against the error budget. Tracking the error budget lets you know whether the service is achieving the performance that you want over a longer period of time. Time window exclusions Time window exclusions is a block of time with a defined start and end date. This time period is excluded from the SLO's performance metrics and you can schedule one-time or recurring time exclusions windows. For example, scheduled maintenance. Note • For period-based SLOs, SLI data in the exclusion window is considered as non-breaching. • For request-based SLOs, all good and bad requests in the exclusion window are excluded. • When an interval for a request-based SLO is completely excluded, a default attainment rate metric of 100% is published. • You can only specify time windows with a start date in the future. Calculate error budget and attainment for request-based SLOs After you have created an SLO, you can retrieve error budget reports for it. An error budget is the amount of requests that your application can be non-compliant with the SLO's goal, and still have your application meet the goal. For a request-based SLO, the remaining error budget is dynamic and can increase or decrease, depending on the ratio of good requests to total requests The following table illustrates the calculation for a request-based SLO with an interval of 5 days and 85% attainment goal. In this example, we assume there is no traffic before Day 1. The SLO did not meet the goal on Day 10. Calculate error budget and attainment for request-based SLOs 1571 Amazon CloudWatch User Guide Time Total requests Bad requests Accumulative total requests Accumulat ive total Request- based Total budget in last 5 days good attainment requests Remaining budget requests 1 1 1 0 5 2 3 6 1 5 10 15 16 40 60 56 61 75 63 57 10 5 1 24 20 6 10 15 12 Day 1 Day 2 Day 3 Day 4 Day 5 Day 6 Day 7 Day 8 Day 9 Day 10 Final attainmen t for last 5 days requests in last 5 days 9 13 13 37 52 47 50 59 46 40 9/10 = 90% 1.5 13/15=86% 2.3 13/16=81% 2.4 37/40=92% 6.0 52/60=87% 9.0 47/56=84% 8.4 50/61=82% 9.2 59/75=79% 11.3 46/63=73% 9.5 40/57=70% 8.5 70% 0.5 0.3 -0.6 3.0 1.0 -0.6 -1.8 -4.7 -7.5 -8.5 Calculate burn rates and optionally set burn rate alarms You can use Application Signals to calculate the burn rates for your service level objectives. A burn rate is a metric that indicates how fast the service is consuming the error budget, relative to the attainment goal of the SLO. It's expressed as a mutliple factor of the
acw-ug-419
acw-ug.pdf
419
9 13 13 37 52 47 50 59 46 40 9/10 = 90% 1.5 13/15=86% 2.3 13/16=81% 2.4 37/40=92% 6.0 52/60=87% 9.0 47/56=84% 8.4 50/61=82% 9.2 59/75=79% 11.3 46/63=73% 9.5 40/57=70% 8.5 70% 0.5 0.3 -0.6 3.0 1.0 -0.6 -1.8 -4.7 -7.5 -8.5 Calculate burn rates and optionally set burn rate alarms You can use Application Signals to calculate the burn rates for your service level objectives. A burn rate is a metric that indicates how fast the service is consuming the error budget, relative to the attainment goal of the SLO. It's expressed as a mutliple factor of the baseline error rate. The burn rate is calculated according to the baseline error rate, which depends on the attainment goal. The attainment goal is the percentage of either healthy time periods or successful requests Calculate burn rates and optionally set burn rate alarms 1572 Amazon CloudWatch User Guide that must be achieved to meet the SLO goal. The baseline error rate is (100% - attainment goal percentage), and this number would use up the exact complete error budget at the end of the SLO's time interval. So an SLO with an attainment goal of 99% would have a baseline error rate of 1%. Monitoring the burn rate tells us how far off we are from the baseline error rate. Again taking the example of an attainment goal of 99%, the following is true: • Burn rate = 1: If the burn rate remains exactly at the baseline error rate all the time, we meet exactly the SLO goal. • Burn rate < 1: If the burn rate is lower than the baseline error rate, we are on track to exceed the SLO goal. • Burn rate > 1: If the burn rate is higher than baseline error rate, we have chance to fail the SLO goal. When you create burn rates for your SLOs, you can also choose to create CloudWatch alarms at the same time to monitor the burn rates. You can set a threshold for the burn rates and the alarms can automatically notify you if the burn rate metrics are breaching the threshold that you set. For example, a burn rate nearing its threshold can let you know that the SLO is burning through the error budget faster than your team can tolerate and your team might need to slow down churn in the application to make sure that long-term performance goals are met. Creating alarms incurs charges. For more information about CloudWatch pricing, see Amazon CloudWatch Pricing. Calculate the burn rate To calculate the burn rate, you must specify a look-back window. The look-back window is the time duration over which to measure the error rate. burn rate = error rate over the look-back window / (100% - attainment goal) Note When there is no data for the burn rate period, Application Signals calculates the burn rate based on attainment. Calculate burn rates and optionally set burn rate alarms 1573 Amazon CloudWatch User Guide The error rate is calculated as the ratio of the number of bad events over the total number of events during the burn rate window: • For period-based SLOs, error rate is calculated as bad periods divided by total periods. The total periods represents the entirety of periods during the look-back window. • For request-based SLOs, this is a measure of bad requests divided by total requests. The total number of requests is the number of requests during the look-back window. The look-back window must be a multiple of the SLO period time, and must be less than the SLO interval. Determine the appropriate threshold for a burn rate alarm When you configure a burn rate alarm, you need to choose a value for the burn rate as the alarm threshold. The value for this threshold depends on the SLO interval length and look-back window, and depends on the which method or mental model that your team wants to adopt. There are two main methods available for determining the threshold. Method 1: Determine the percentage of estimated total error budget your team is willing to burn in the look-back window. If you want to get alarmed when X% of the estimated error budget is spent within the last burn rate look-back hours, the burn rate threshold is the following: burn rate threshold = X% * SLO interval length / look-back window size For example, 5% of a 30-day (720-hour) error budget spent over one hour requires a burn rate of 5% * 720 / 1 = 36. Therefore, if the burn rate look-back window is1 hour, we set the burn rate threshold to be 36. You can use the CloudWatch console to create burn rate alarms using this method. You can specify the number X, and the threshold is determined using the
acw-ug-420
acw-ug.pdf
420
budget is spent within the last burn rate look-back hours, the burn rate threshold is the following: burn rate threshold = X% * SLO interval length / look-back window size For example, 5% of a 30-day (720-hour) error budget spent over one hour requires a burn rate of 5% * 720 / 1 = 36. Therefore, if the burn rate look-back window is1 hour, we set the burn rate threshold to be 36. You can use the CloudWatch console to create burn rate alarms using this method. You can specify the number X, and the threshold is determined using the above formula. The SLO interval length is determined based on the SLO interval type: • For SLOs with a rolling interval, it’s the length of the interval in hours. • For SLOs with a calendar-based interval: • If the unit is days or weeks, it’s the length of the interval in hours. Calculate burn rates and optionally set burn rate alarms 1574 Amazon CloudWatch User Guide • If the unit is a month, we take 30 days as the estimated length and convert it to hours. Method 2: Determine the time unitl budget exhaustion for the next interval To have the alarm notify you when the current error rate in the most recent look-back window indicates that the time until budget exhaustion is less than X hours away (assuming the budget remaining is currently 100%), you can use the following formula to determine the burn rate threshold. burn rate threshold = SLO interval length / X We emphasize that the time until budget exhaustion (X) in the above formula assumes that the total budget remaining is currently 100%, and therefore it does not take into account the amount of budget that has already been burnt in this interval. We can also think of it as the time till budget exhaustion for the next interval. Walkthroughs for burn rate alarms As an example, let's take an SLO with a 28-day rolling interval. Setting a burn rate alarm for this SLO involves two steps: 1. Set the burn rate and the look-back window. 2. Crete a CloudWatch alarm that monitors the burn rate. To get started, determine how much of the total error budget the service is willing to burn through within a specific time frame. In other words, statie your objective by using this sentence: "I want to get alerted when X% of my total error budget is consumed within M minutes." For example, you might want to set the objective to be alerted when 2% of the total error budget is consumed within 60 minutes. To set the burn rate, you first define the look-back window. The look-back windows is M, which in this example is 60 minutes. Next, you create the CloudWatch alarm. When you do so, you must specify a threshold for the burn rate. If burn rate exceeds this threshold, the alarm will notify you. To find the threshold,use the following formula: burn rate threshold = X% * SLO interval length/ look-back window size Calculate burn rates and optionally set burn rate alarms 1575 Amazon CloudWatch User Guide In this example, X is 2 because we want to be alerted if 2% of the error budget is consumed within 60 minutes. The interval length is 40,320 minutes (28 days), and 60 minutes is the look-back window, so the answer is: burn rate threshold = 2% * 40,320 / 60 = 13.44. In this example, you would set 13.44 as the alarm threshold. Multiple alarms with different windows By setting up alarms on multiple look-back windows, you can quickly detect sharp error rate increases with the short window and at the same time detect smaller error rate increases that eventually deplete the error budget if they remain unnoticed. Additionally, you could set a composite alarm on a burn rate with long window and on a burn rate with a short window (1/12th of the long window), and be informed only when both of the burn rates breach a threshold. This way, you can ensure that you get alerted only for situations that are still happening. For more information about composite alarms in CloudWatch, see Combining alarms. Note You can set a metric alarm on a burn rate when you create the burn rate. To set a compoaite alarm on multiple burn rate alarms, you must use the instructions in Create a composite alarm. One composite alarm strategy recommended in the Google Site Reliability Engineering workbook includes three composite alarms: • One composite alarm that watches a pair of alarms, one with a one-hour window and one with a five-minute window. • A second composite alarm that watches a pair of alarms, one with a six-hour window and one with a 30-minute window. • A third composite alarm that
acw-ug-421
acw-ug.pdf
421
can set a metric alarm on a burn rate when you create the burn rate. To set a compoaite alarm on multiple burn rate alarms, you must use the instructions in Create a composite alarm. One composite alarm strategy recommended in the Google Site Reliability Engineering workbook includes three composite alarms: • One composite alarm that watches a pair of alarms, one with a one-hour window and one with a five-minute window. • A second composite alarm that watches a pair of alarms, one with a six-hour window and one with a 30-minute window. • A third composite alarm that watches a pair of alarms, one with a three-day window and one with a six-hour window. The steps to do this set up are the following: Calculate burn rates and optionally set burn rate alarms 1576 Amazon CloudWatch User Guide 1. Create five burn rates, with windows of five minutes, 30 minutes, one hour, six hours, and three days. 2. Create the following three pairs of CloudWatch alarms. Each pair includes one long window and one short window that is 1/12th of the long window, and the thresholds are determined by using the steps in Determine the appropriate threshold for a burn rate alarm. When you calculate the threshold for each alarm in the pair, use the longer look-back window of the pair in your calculation. • Alarms on the 1-hour and 5-minute burn rates (the threshold is determined by 2% of the total budget) • Alarms on the 6-hour and 30-minute burn rates (the threshold is determined by 5% of the total budget) • Alarms on the 3-day and 6-hour burn rates (the threshold is determined by 10% of the total budget) 3. For each of these pairs, create a composite alarm to get alerted when both of the individual alarms go into ALARM state. For more information about creating composite alarms, see Create a composite alarm. For example, if your alarms for the first pair (one-hour window and five-minute window) are named OneHourBurnRate and FiveMinuteBurnRate, the CloudWatch composite alarm rule would be ALARM(OneHourBurnRate) AND ALARM(FiveMinuteBurnRate) The previous strategy is possible only for SLOs with interval length of at least three hours. For SLOs with shorter interval lengths, we recommend that you start with one pair of burn rate alarms where one alarm has a look-back window that is 1/12th of the look-back window of the other alarm. Then set a composite alarm on this pair. Create an SLO We recommend that you set both latency and availability SLOs on your critical applications. These metrics collected by Application Signals align with common business goals. You can also set SLOs on any CloudWatch metric or any metric math expression that results in a single time series. The first time that you create an SLO in your account, CloudWatch automatically creates the AWSServiceRoleForCloudWatchApplicationSignals service-linked role in your account, if it doesn't already exist. This service-linked role allows CloudWatch to collect CloudWatch Logs data, Create an SLO 1577 Amazon CloudWatch User Guide X-Ray trace data, CloudWatch metrics data, and tagging data from applications in your account. For more information about CloudWatch service-linked roles, see Using service-linked roles for CloudWatch. When you create an SLO, you specify whether it is a period-based SLO or a request-based SLO. Each type of SLO has a different way of evaluating your application's performance against its attainment goal. • A period-based SLO uses defined periods of time within a specified total time interval. For each period of time, Application Signals determines whether the application met its goal. The attainment rate is calculated as the number of good periods/number of total periods. For example, for a period-based SLO, meeting an attainment goal of 99.9% means that within your interval, your application must meet its performance goal during at least 99.9% of the time periods. • A request-based SLO doesn't use pre-defined periods of time. Instead, the SLO measures number of good requests/number of total requests during the interval. At any time, you can find the ratio of good requests to total requests for the interval up to the time stamp that you specify, and measure that ratio against the goal set in your SLO. Topics • Create a period-based SLO • Create a request-based SLO Create a period-based SLO Use the following procedure to create a period-based SLO. To create a period-based SLO 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Service Level Objectives (SLO). 3. Choose Create SLO. 4. Enter a name for the SLO. Including the name of a service or operation, along with appropriate keywords such as latency or availability, will help you quickly identify what the SLO status indicates during triage. Create an SLO 1578 Amazon CloudWatch User Guide 5. For Set Service Level Indicator (SLI), do one of
acw-ug-422
acw-ug.pdf
422
period-based SLO • Create a request-based SLO Create a period-based SLO Use the following procedure to create a period-based SLO. To create a period-based SLO 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Service Level Objectives (SLO). 3. Choose Create SLO. 4. Enter a name for the SLO. Including the name of a service or operation, along with appropriate keywords such as latency or availability, will help you quickly identify what the SLO status indicates during triage. Create an SLO 1578 Amazon CloudWatch User Guide 5. For Set Service Level Indicator (SLI), do one of the following: • To set the SLO on either of the standard application metrics Latency or Availability: a. b. c. d. e. Choose Service Operation. Select an account that this SLO will monitor. Select the service that this SLO will monitor. Select the operation that this SLO will monitor. For Select a calculation method, choose Periods. The Select service and Select operation drop-downs are populated by services and operations that have been active within the past 24 hours. f. Choose either Availability or Latency and then set the threshold. • To set the SLO on any CloudWatch metric or a CloudWatch metric math expression: a. Choose CloudWatch Metric. b. Choose Select CloudWatch metric. The Select metric screen appears. Use the Browse or Query tabs to find the metric you want, or create a metric math expression. After you select the metric that you want, choose the Graphed metrics tab and select the Statistic and Period to use for the SLO. Then choose Select metric. For more information about these screens, see Graph a metric and Add a math expression to a CloudWatch graph. For Select a calculation method, choose Periods. For Set condition, select a comparison operator and threshold for the SLO to use as the indicator of success. c. d. • To set the SLO on the dependency of a service on either of the standard application metrics Latency or Availability: a. Choose Service Dependency. b. Under Select a service, select the service that this SLO will monitor. c. Create an SLO Based on the selected service, under Select an operation, you can select one specific operation or select All operations to use the metrics from all operations of this service that calls a dependency. 1579 Amazon CloudWatch User Guide d. Under Select a dependency, you can search and select the required dependency for which you want to measure the reliability. After you select the dependency, you can view the updated graph and historical data based on the dependency. 6. 7. If you selected Service Operation or Service Dependency in step 5, set the period length for this SLO. Set the interval and attainment goal for the SLO. For more information about intervals and attainment goals and how they work together, see SLO concepts. 8. (Optional) For Set SLO burn rates do the following: • Set the length (in minutes) of the look-back window for the burn rate. For information about how to choose this length, see Walkthroughs for burn rate alarms. • To create more burn rates for this SLO, choose Add more burn rates and set the look-back window for the additional burn rates. 9. (Optional) Create burn rate alarms by doing the following: • Under Set burn rate alarms select the check box for each burn rate that you want to create an alarm for. For each of these alarms, do the following: • Specify the Amazon SNS topic to use for notifications when the alarm goes into ALARM state. • Either set a burn rate threshold or specify the percentage of the estimated total budget burnt in the last look-back window you want to stay below. If you set the percentage of estimated total budget burned, the burn rate threshold is calculated for you and used in the alarm. To either decide what threshold to set or to understand how this option is used to compute the burn rate threshold, see Determine the appropriate threshold for a burn rate alarm. 10. (Optional) Set one or more CloudWatch alarms or a warning threshold for the SLO. a. CloudWatch alarms can use Amazon SNS to proactively notify you if an application is unhealthy based on its SLI performance. To create an alarm, select one of the alarm check boxes and enter or create the Amazon SNS topic to use for notifications when the alarm goes into ALARM state. For more information about CloudWatch alarms, see Using Amazon CloudWatch alarms. Creating Create an SLO 1580 Amazon CloudWatch User Guide alarms incurs charges. For more information about CloudWatch pricing, see Amazon CloudWatch Pricing. b. If you set a warning threshold, it appears in Application Signals screens to help you identify SLOs that are in danger of being unmet, even
acw-ug-423
acw-ug.pdf
423
you if an application is unhealthy based on its SLI performance. To create an alarm, select one of the alarm check boxes and enter or create the Amazon SNS topic to use for notifications when the alarm goes into ALARM state. For more information about CloudWatch alarms, see Using Amazon CloudWatch alarms. Creating Create an SLO 1580 Amazon CloudWatch User Guide alarms incurs charges. For more information about CloudWatch pricing, see Amazon CloudWatch Pricing. b. If you set a warning threshold, it appears in Application Signals screens to help you identify SLOs that are in danger of being unmet, even if they're currently healthy. To set a warning threshold, enter the threshold value in Warning threshold. When the SLO's error budget is lower than the warning threshold, the SLO is marked with Warning in several Application Signals screens. Warning thresholds also appear on error budget graphs. You can also create an SLO warning alarm that's based on the warning threshold. 11. (Optional) For Set SLO time window exclusion, do the following: • Under Exclude time window, set the time window to be excluded from the SLO performance metrics. You can choose Set time window and enter the Start window for every hour or month or you can choose Set time window with CRON and enter the CRON expression. • Under Repeat, set if this time window exclusion is recurring or not. • (Optional) Under Add reason, you can choose to enter a reason for the time window exclusion. For example, scheduled maintenance. • Select Add time window to add upto 10 time exclusion windows. 12. To add tags to this SLO, choose the Tags tab and then choose Add new tag. Tags can help you manage, identify, organize, search for, and filter resources. For more information about tagging, see Tagging your AWS resources. Note If the application this SLO is related to is registered in AWS Service Catalog AppRegistry, you can use the awsApplication tag to associate this SLO with that application in AppRegistry. For more information, see What is AppRegistry? 13. Choose Create SLO. If you also chose to create one or more alarms, the button name changes to reflect this. Create a request-based SLO Use the following procedure to create a request-based SLO. Create an SLO 1581 Amazon CloudWatch To create a request-based SLO User Guide 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Service Level Objectives (SLO). 3. Choose Create SLO. 4. Enter a name for the SLO. Including the name of a service or operation, along with appropriate keywords such as latency or availability, will help you quickly identify what the SLO status indicates during triage. 5. For Set Service Level Indicator (SLI), do one of the following: • To set the SLO on either of the standard application metrics Latency or Availability: a. b. c. d. e. Choose Service Operation. Select the service that this SLO will monitor. Select the operation that this SLO will monitor. For Select a calculation method, choose Requests. The Select service and Select operation drop-downs are populated by services and operations that have been active within the past 24 hours. f. Choose either Availability or Latency. If you choose Latency, set the threshold. • To set the SLO on any CloudWatch metric or a CloudWatch metric math expression: a. b. Choose CloudWatch Metric. For Define target requests, do the following: i. ii. Choose whether you want to measure Good Requests or Bad Requests. Choose Select CloudWatch metric. This metric will be the numerator of the ratio of target requests to total requests. If you use a latency metric, use the Trimmed count (TC) statistics. If the threshold is 9 ms and you're using the less than (<) comparison operator, then use threshold TC (:threshold - 1). For more information about TC, see Syntax. The Select metric screen appears. Use the Browse or Query tabs to find the metric you want, or create a metric math expression. c. For Define total requests, choose the CloudWatch metric that you want to use for the source. This metric will be the denominator of the ratio of target requests to total requests. Create an SLO 1582 Amazon CloudWatch User Guide The Select metric screen appears. Use the Browse or Query tabs to find the metric you want, or create a metric math expression. After you select the metric that you want, choose the Graphed metrics tab and select the Statistic and Period to use for the SLO. Then choose Select metric. If you use a latency metric which emits one data point per request, use the Sample count statistics to count the number of total requests. For more information about these screens, see Graph a metric and Add a math expression to a CloudWatch graph. • To set the
acw-ug-424
acw-ug.pdf
424
Guide The Select metric screen appears. Use the Browse or Query tabs to find the metric you want, or create a metric math expression. After you select the metric that you want, choose the Graphed metrics tab and select the Statistic and Period to use for the SLO. Then choose Select metric. If you use a latency metric which emits one data point per request, use the Sample count statistics to count the number of total requests. For more information about these screens, see Graph a metric and Add a math expression to a CloudWatch graph. • To set the SLO on the dependency of a service on either of the standard application metrics Latency or Availability: a. Choose Service Dependency. b. Under Select a service, select the service that this SLO will monitor. c. Based on the selected service, under Select an operation, you can select one specific operation or select All operations to use the metrics from all operations of this service that calls a dependency. d. Under Select a dependency, you can search and select the required dependency for which you want to measure the reliability. After you select the dependency, you can view the updated graph and historical data based on the dependency. 6. Set the interval and attainment goal for the SLO. For more information about intervals and attainment goals and how they work together, see SLO concepts. 7. (Optional) For Set SLO burn rates do the following: • Set the length (in minutes) of the look-back window for the burn rate. For information about how to choose this length, see Walkthroughs for burn rate alarms. • To create more burn rates for this SLO, choose Add more burn rates and set the look-back window for the additional burn rates. 8. (Optional) Create burn rate alarms by doing the following: • Under Set burn rate alarms select the check box for each burn rate that you want to create an alarm for. For each of these alarms, do the following: Create an SLO 1583 Amazon CloudWatch User Guide • Specify the Amazon SNS topic to use for notifications when the alarm goes into ALARM state. • Either set a burn rate threshold or specify the percentage of the estimated total budget burnt in the last look-back window you want to stay below. If you set the percentage of estimated total budget burned, the burn rate threshold is calculated for you and used in the alarm. To either decide what threshold to set or to understand how this option is used to compute the burn rate threshold, see Determine the appropriate threshold for a burn rate alarm. 9. (Optional) Set one or more CloudWatch alarms or a warning threshold for the SLO. a. CloudWatch alarms can use Amazon SNS to proactively notify you if an application is unhealthy based on its SLI performance. To create an alarm, select one of the alarm check boxes and enter or create the Amazon SNS topic to use for notifications when the alarm goes into ALARM state. For more information about CloudWatch alarms, see Using Amazon CloudWatch alarms. Creating alarms incurs charges. For more information about CloudWatch pricing, see Amazon CloudWatch Pricing. b. If you set a warning threshold, it appears in Application Signals screens to help you identify SLOs that are in danger of being unmet, even if they're currently healthy. To set a warning threshold, enter the threshold value in Warning threshold. When the SLO's error budget is lower than the warning threshold, the SLO is marked with Warning in several Application Signals screens. Warning thresholds also appear on error budget graphs. You can also create an SLO warning alarm that's based on the warning threshold. 10. (Optional) For Set SLO time window exclusion, do the following: • Under Exclude time window, set the time window to be excluded from the SLO performance metrics. You can choose Set time window and enter the Start window for every hour or month or you can choose Set time window with CRON and enter the CRON expression. • Under Repeat, set if this time window exclusion is recurring or not. • (Optional) Under Add reason, you can choose to enter a reason for the time window exclusion. For example, scheduled maintenance. • Select Add time window to add upto 10 time exclusion windows. Create an SLO 1584 Amazon CloudWatch User Guide 11. To add tags to this SLO, choose the Tags tab and then choose Add new tag. Tags can help you manage, identify, organize, search for, and filter resources. For more information about tagging, see Tagging your AWS resources. Note If the application this SLO is related to is registered in AWS Service Catalog AppRegistry, you can use the awsApplication tag to associate this SLO with that application in AppRegistry.
acw-ug-425
acw-ug.pdf
425
reason for the time window exclusion. For example, scheduled maintenance. • Select Add time window to add upto 10 time exclusion windows. Create an SLO 1584 Amazon CloudWatch User Guide 11. To add tags to this SLO, choose the Tags tab and then choose Add new tag. Tags can help you manage, identify, organize, search for, and filter resources. For more information about tagging, see Tagging your AWS resources. Note If the application this SLO is related to is registered in AWS Service Catalog AppRegistry, you can use the awsApplication tag to associate this SLO with that application in AppRegistry. For more information, see What is AppRegistry? 12. Choose Create SLO. If you also chose to create one or more alarms, the button name changes to reflect this. View and triage SLO status You can quickly see the health of your SLOs using either the Service Level Objectives or the Services options in the CloudWatch console. The Services view provides an at-a-glance view of the ratio of unhealthy services, calculated based on SLOs that you have set. For more information about using the Services option, see Monitor the operational health of your applications with Application Signals. The Service Level Objectives view provides a macro view of your organization. You can see the met and unmet SLOs as a whole. This gives you a view of how many of your services and operations are performing to your expectations over longer periods of time, according to the SLIs that you chose. To view all of your SLOs using the Service Level Objectives view 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Service Level Objectives (SLO). The Service Level Objectives (SLO) list appears. You can quickly see the current status of your SLOs in the SLI status column. To sort the SLOs so that all the unhealthy ones are at the top of the list, choose the SLI status column until the unhealthy SLOs are all at the top. View and triage SLO status 1585 Amazon CloudWatch User Guide The SLO table has the following default columns. You can adjust which columns are displayed by choosing the gear icon above the list. For more information about goals, SLIs, attainment, and intervals, see SLO concepts. • The name of the SLO. • The Goal column displays the percentage of periods during each interval that must successfully meet the SLI threshold for the SLO goal to be met. It also displays the interval length for the SLO. • The SLI status displays whether the current operational state of the application is healthy or not. If any period during the currently selected time range was unhealthy for the SLO, then the SLI status displays Unhealthy. • If this SLO is configured to monitor a dependency, the Dependency and Remote Operation columns will show the details about that dependency relationship. • The Ending attainment is the attainment level achieved as of the end of the selected time range. Sort by this column to see the SLOs that are most in danger of not being met. • The Attainment delta is the difference in attainment level between the start and end of the selected time range. A negative delta means that the metric is trending in a downward direction. Sort by this column to see the latest trends of the SLOs. • The Ending error budget (%) is the percentage of total time in the period that can have unhealthy periods and still have the SLO be achieved successfully. If you set this to 5%, and the SLI is unhealthy in 5% or fewer of the remaining periods in the interval, the SLO is still achieved successfully. • The Error budget delta is the difference in error budget between the start and end of the selected time range. A negative delta means that the metric is trending in a failing direction. • The Ending error budget (time) is the amount of actual time in the interval that can be unhealthy and still have the SLO be achieved successfully. For example, if this is 14 minutes, then if the SLI is unhealthy for fewer than 14 minutes during the remaining interval, the SLO will still be achieved successfully. • The Ending error budget (requests) is the amount of requests in the interval that can be unhealthy and still have the SLO be achieved successfully. For request-based SLOs, this value is dynamic and can fluctuate as the cumulative total number of requests changes over time. • The Service, Operation, and Type columns display information about what service and operation this SLO is set for. View and triage SLO status 1586 Amazon CloudWatch User Guide 3. To see the attainment and error budget graphs for an SLO, choose the radio button next to the SLO name.
acw-ug-426
acw-ug.pdf
426
still be achieved successfully. • The Ending error budget (requests) is the amount of requests in the interval that can be unhealthy and still have the SLO be achieved successfully. For request-based SLOs, this value is dynamic and can fluctuate as the cumulative total number of requests changes over time. • The Service, Operation, and Type columns display information about what service and operation this SLO is set for. View and triage SLO status 1586 Amazon CloudWatch User Guide 3. To see the attainment and error budget graphs for an SLO, choose the radio button next to the SLO name. The graphs at the top of the page display the SLO attainment and Error budget status. A graph about the SLI metric associated with this SLO is also displayed. 4. To further triage an SLO that is not meeting its goal, choose the service name, operation name, or dependency name associated with that SLO. You are taken to the details page where you can triage further. For more information, see View detailed service activity and operational health with the service detail page. 5. To change the time range of the charts and tables on the page, choose a new time range near the top of the screen. Edit an existing SLO Follow these steps to edit an existing SLO. When you edit an SLO, you can change only the threshold, interval, attainment goal, and tags. To change other aspects such as service, operation, or metric, create a new SLO instead of editing an existing one. Changing part of an SLO core configuration, such as period or threshold, invalidates all the previous data points and assessments about attainment and health. It effectively deletes and re- creates the SLO. Note If you edit an SLO, alarms associated with that SLO are not automatically updated. You might need to update the alarms to keep them in sync with the SLO. To edit an existing SLO 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Service Level Objectives (SLO). 3. Choose the radio button next to the SLO that you want to edit, and choose Actions, Edit SLO. 4. Make your changes, then choose Save changes. Edit an existing SLO 1587 Amazon CloudWatch Delete an SLO Follow these steps to delete an existing SLO. User Guide Note When you delete an SLO, alarms associated with that SLO are not automatically deleted. You'll need to delete them yourself. For more information, see Managing alarms. To delete an SLO 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Service Level Objectives (SLO). 3. Choose the radio button next to the SLO that you want to edit, and choose Actions, Delete SLO. 4. Choose Confirm. Transaction Search Transaction Search is an interactive analytics experience you can use to get complete visibility of your application transaction spans. Spans are the fundamental units of operation in a distributed trace and represent specific actions or tasks in an application or system. Every span records details about a particular segment of the transaction. These details include start and end times, duration, and associated metadata, which can include business attributes like customer IDs and order IDs. Spans are arranged in a parent-child hierarchy. This hierarchy forms a complete trace, mapping the flow of a transaction across different components or services. Delete an SLO 1588 Amazon CloudWatch User Guide Topics • Benefits • How it works • Pricing • Getting started with Transaction Search • Spans • Adding custom attributes • Troubleshooting application issues Benefits The following are benefits of using Transaction Search: Capture all spans Ingest 100 percent of spans as structured logs in CloudWatch to get complete visibility. This prevents broken traces and provides you the ability to view large traces containing up to 10,000 spans for detailed insights. Index spans as trace summaries Benefits 1589 Amazon CloudWatch User Guide Index a percentage of spans as trace summaries in X-Ray to unlock end to end trace search and analytics. Investigate transaction issues with free form analytics Search all span attributes in the visual editor to identify the cause of issues in application transactions. This helps you answer questions about application performance and the impact end- users make based on their application transactions. Send spans to the OpenTelemetry endpoint Send spans to the OpenTelemetry endpoint for X-Ray traces. These spans are stored in the semantic convention format with W3C trace IDs. Note X-Ray traces automatically convert to the semantic convention format before they're stored in a log group called aws/spans. For more information, see The span log group. Use CloudWatch Logs with spans Use metric filters to extract custom metrics, subscription filters to forward data, and data masking to protect personally identifiable information. Troubleshoot application issues Access application dashboards, metrics, and topology when you
acw-ug-427
acw-ug.pdf
427
impact end- users make based on their application transactions. Send spans to the OpenTelemetry endpoint Send spans to the OpenTelemetry endpoint for X-Ray traces. These spans are stored in the semantic convention format with W3C trace IDs. Note X-Ray traces automatically convert to the semantic convention format before they're stored in a log group called aws/spans. For more information, see The span log group. Use CloudWatch Logs with spans Use metric filters to extract custom metrics, subscription filters to forward data, and data masking to protect personally identifiable information. Troubleshoot application issues Access application dashboards, metrics, and topology when you enable Application Signals for all spans sent to CloudWatch. How it works When you enable Transaction Search, you unlock multiple capabilities, including features in Application Signals and CloudWatch Logs. How it works 1590 Amazon CloudWatch User Guide If you send traces to X-Ray, you can get started by enabling Transaction Search in the console or with the API. If you don't send traces to X-Ray, you can use the CloudWatch Application Signals that provides pre-packaged OpenTelemetry setup with AWS Distro fro OpenTelemetry (ADOT), CloudWatch Agent, or use OpenTelemetry directly. When you enable Transaction Search, spans sent to X-Ray are ingested in a log group called aws/ spans. CloudWatch uses these spans to generate a curated application performance monitoring (APM) experience in CloudWatch Application Signals. This provides you the ability to search and analyze spans, as well as use CloudWatch Logs capabilities like anomaly and pattern detection. You can even use custom metric extraction . CloudWatch Application Signals provides you with a unified, application-centric view of your applications, services, and dependencies. It also helps you monitor and triage application health. You can also explore spans using the interactive search and analytics experience in CloudWatch to answer any questions related to application performance or end-user impact with Transaction Search. Detect the impact on end users, find transactions in context of those issues using relevant attributes, such as customer name or order number. You can correlate transactions to business events, such as failed payments, and dive into interactions between application components to establish a root cause. With CloudWatch, you get complete application transaction coverage with correlated insights, helping you to accelerate mean time to resolution. Pricing For information about pricing, see Amazon CloudWatch Pricing. Pricing 1591 Amazon CloudWatch User Guide Getting started with Transaction Search If you send traces to X-Ray, you can enable Transaction Search in the CloudWatch console or with the CloudWatch API. Topics • Prerequisites • Enable transaction search • Using Transaction Search with AWS CloudFormation Prerequisites Before you can enable Transaction Search, you must create a role with the following permissions. { "Version": "2012-10-17", "Statement": [ { "Sid": "TransactionSearchXRayPermissions", "Effect": "Allow", "Action": [ "xray:GetTraceSegmentDestination", "xray:UpdateTraceSegmentDestination", "xray:GetIndexingRules", "xray:UpdateIndexingRule" ], "Resource": "*" }, { "Sid": "TransactionSearchLogGroupPermissions", "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutRetentionPolicy" ], "Resource": [ "arn:aws:logs:*:*:log-group:/aws/application-signals/data:*", "arn:aws:logs:*:*:log-group:aws/spans:*" ] }, Getting started with Transaction Search 1592 User Guide Amazon CloudWatch { "Sid": "TransactionSearchLogsPermissions", "Effect": "Allow", "Action": [ "logs:PutResourcePolicy", "logs:DescribeResourcePolicies" ], "Resource": [ "*" ] }, { "Sid": "TransactionSearchApplicationSignalsPermissions", "Effect": "Allow", "Action": [ "application-signals:StartDiscovery" ], "Resource": "*" }, { "Sid": "CloudWatchApplicationSignalsCreateServiceLinkedRolePermissions", "Effect": "Allow", "Action": "iam:CreateServiceLinkedRole", "Resource": "arn:aws:iam::*:role/aws-service-role/application- signals.cloudwatch.amazonaws.com/AWSServiceRoleForCloudWatchApplicationSignals", "Condition": { "StringLike": { "iam:AWSServiceName": "application-signals.cloudwatch.amazonaws.com" } } }, { "Sid": "CloudWatchApplicationSignalsGetRolePermissions", "Effect": "Allow", "Action": "iam:GetRole", "Resource": "arn:aws:iam::*:role/aws-service-role/application- signals.cloudwatch.amazonaws.com/AWSServiceRoleForCloudWatchApplicationSignals" } ] } Getting started with Transaction Search 1593 Amazon CloudWatch Note User Guide To use Transaction Search and other CloudWatch features, add the CloudWatchReadOnlyAccess policy to your role. For information about how to create a role, see IAM role creation. Enable transaction search You can enhance Lambda observability by using transaction search, which enables the capture of all trace spans for Lambda function invocation without sampling. This feature allows you to collect 100% of the spans for your functions, unaffected by the sampled flag in trace context propagation. This ensures that there is no additional impact to downstream dependent services. By enabling transaction search on Lambda, you gain complete visibility into your function performance and you can troubleshoot rarely occurring issues. To get started, see Transaction Search. Enabling Transaction Search in the console The following procedure describes how to enable Transaction Search in the console. To enable Transaction Search in the CloudWatch console 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. From the navigation pane, under Application Signals, choose Transaction Search. 3. Choose Enable Transaction Search. 4. Select the box to ingest spans as structured logs, and enter a percentage of spans to be indexed. You can index spans at 1% for free and change the percentage later based on your requirements. Enabling Transaction Search using an API The following procedure describes how to enable Transaction Search using an API. Step 1. Create a policy that grants access to ingest spans in CloudWatch Logs When using the AWS CLI or SDK to enable Transaction
acw-ug-428
acw-ug.pdf
428
Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. From the navigation pane, under Application Signals, choose Transaction Search. 3. Choose Enable Transaction Search. 4. Select the box to ingest spans as structured logs, and enter a percentage of spans to be indexed. You can index spans at 1% for free and change the percentage later based on your requirements. Enabling Transaction Search using an API The following procedure describes how to enable Transaction Search using an API. Step 1. Create a policy that grants access to ingest spans in CloudWatch Logs When using the AWS CLI or SDK to enable Transaction Search, you must configure permissions using a resource-based policy with PutResourcePolicy. Getting started with Transaction Search 1594 Amazon CloudWatch Example policy User Guide The following example policy allows X-Ray to send traces to CloudWatch Logs { "Version": "2012-10-17", "Statement": [ { "Sid": "TransactionSearchXRayAccess", "Effect": "Allow", "Principal": { "Service": "xray.amazonaws.com" }, "Action": "logs:PutLogEvents", "Resource": [ "arn:partition:logs:region:account-id:log-group:aws/spans:*", "arn:partition:logs:region:account-id:log-group:/aws/application- signals/data:*" ], "Condition": { "ArnLike": { "aws:SourceArn": "arn:partition:xray:region:account-id:*" }, "StringEquals": { "aws:SourceAccount": "account-id" } } } ] } Example command The following example shows how to format your AWS CLI command with PutResourcePolicy. aws logs put-resource-policy --policy-name MyResourcePolicy --policy-document '{ "Version": "2012-10-17", "Statement": [ { "Sid": "TransactionSearchXRayAccess", "Effect": "Allow", "Principal": { "Service": "xray.amazonaws.com" }, "Action": "logs:PutLogEvents", "Resource": [ "arn:partition:logs:region:account-id:log- group:aws/spans:*", "arn:partition:logs:region:account-id:log-group:/aws/ application-signals/data:*" ], "Condition": { "ArnLike": { "aws:SourceArn": "arn:partition:logs:region:account-id:*" }, "StringEquals": { "aws:SourceAccount": "account-id" } } } ]}' Getting started with Transaction Search 1595 Amazon CloudWatch User Guide Step 2. Configure the destination of trace segments Configure the ingestion of spans with UpdateTraceSegmentDestination. Example command The following example shows how to format your AWS CLI command with UpdateTraceSegmentDestination. aws xray update-trace-segment-destination --destination CloudWatchLogs Step 3. Configure the amount of spans to index Configure your desired sampling percentage with UpdateIndexingRule Example command The following example shows how to format your AWS CLI command with UpdateIndexingRule. aws xray update-indexing-rule --name "Default" --rule '{"Probabilistic": {"DesiredSamplingPercentage": number}}' Note After you enable Transaction Search, it can take ten minutes for spans to become available for search and analysis. Step 4. Verify spans are available for search and analysis To verify spans are available for search and analysis, use GetTraceSegmentDestination. Example commands The following example shows how to format your AWS CLI command with GetTraceSegmentDestination. aws xray get-trace-segment-destination Example response The following example shows the response you can expect when Transaction Search is active. Getting started with Transaction Search 1596 Amazon CloudWatch User Guide { "Destination": "CloudWatchLogs", "Status": "ACTIVE" } Using Transaction Search with AWS CloudFormation You can use AWS CloudFormation to enable and configure X-Ray Transaction Search. Note To create a AWS CloudFormation stack, see Creating your first stack . Prerequisites • You must have access to an AWS account with an IAM user or role that has permissions to use Amazon EC2, Amazon S3, AWS CloudFormation, or have administrative user access. • You must have a Virtual Private Cloud (VPC) that has access to the internet. To keep things simple, you can use the default VPC that comes with your account. The default VPC and default subnets are sufficient for this configuration. • Make sure Transaction Search is disabled before you enable using AWS CDK or AWS CloudFormation. Enabling Transaction Search To enable Transaction Search using CloudFormation, you need to create the following two resources. • AWS::Logs::ResourcePolicy • AWS::XRay::TransactionSearchConfig 1. Create AWS::Logs::ResourcePolicy – Create a resource policy that allows X-Ray to send traces to CloudWatch Logs YAML Resources: Getting started with Transaction Search 1597 Amazon CloudWatch User Guide LogsResourcePolicy: Type: AWS::Logs::ResourcePolicy Properties: PolicyName: TransactionSearchAccess PolicyDocument: !Sub > { "Version": "2012-10-17", "Statement": [ { "Sid": "TransactionSearchXRayAccess", "Effect": "Allow", "Principal": { "Service": "xray.amazonaws.com" }, "Action": "logs:PutLogEvents", "Resource": [ "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log- group:aws/spans:*", "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log- group:/aws/application-signals/data:*" ], "Condition": { "ArnLike": { "aws:SourceArn": "arn:${AWS::Partition}:xray:${AWS::Region}: ${AWS::AccountId}:*" }, "StringEquals": { "aws:SourceAccount": "${AWS::AccountId}" } } } ] } JSON { "Resources": { "LogsResourcePolicy": { "Type": "AWS::Logs::ResourcePolicy", "Properties": { "PolicyName": "TransactionSearchAccess", "PolicyDocument": { Getting started with Transaction Search 1598 Amazon CloudWatch User Guide "Fn::Sub": "{\n \"Version\": \"2012-10-17\",\n \"Statement \": [\n {\n \"Sid\": \"TransactionSearchXRayAccess\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"xray.amazonaws.com \"\n },\n \"Action\": \"logs:PutLogEvents\",\n \"Resource\": [\n \"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log- group:aws/spans:*\",\n \"arn:${AWS::Partition}:logs:${AWS::Region}: ${AWS::AccountId}:log-group:/aws/application-signals/data:*\"\n ],\n \"Condition\": {\n \"ArnLike\": {\n \"aws:SourceArn\": \"arn: ${AWS::Partition}:xray:${AWS::Region}:${AWS::AccountId}:*\"\n },\n \"StringEquals\": {\n \"aws:SourceAccount\": \"${AWS::AccountId}\"\n }\n }\n }\n ]\n}" } } } } } 2. Create and Configure AWS::XRay::TransactionSearchConfig – Create the TransactionSearchConfig resource to enable Transaction Search. YAML Resources: XRayTransactionSearchConfig: Type: AWS::XRay::TransactionSearchConfig JSON { "Resources": { "XRayTransactionSearchConfig": { "Type": "AWS::XRay::TransactionSearchConfig" } } } 3. (Optional) You can set the IndexingPercentage property to control the percentage of spans that will be indexed. YAML Resources: Getting started with Transaction Search 1599 Amazon CloudWatch User Guide XRayTransactionSearchConfig: Type: AWS::XRay::TransactionSearchConfig Properties: IndexingPercentage: 50 JSON { "Resources": { "XRayTransactionSearchConfig": { "Type": "AWS::XRay::TransactionSearchConfig", "Properties": { "IndexingPercentage": 20 } } } } The IndexingPercentage value can be set between 0 and 100. Template examples The following example includes
acw-ug-429
acw-ug.pdf
429
} } 2. Create and Configure AWS::XRay::TransactionSearchConfig – Create the TransactionSearchConfig resource to enable Transaction Search. YAML Resources: XRayTransactionSearchConfig: Type: AWS::XRay::TransactionSearchConfig JSON { "Resources": { "XRayTransactionSearchConfig": { "Type": "AWS::XRay::TransactionSearchConfig" } } } 3. (Optional) You can set the IndexingPercentage property to control the percentage of spans that will be indexed. YAML Resources: Getting started with Transaction Search 1599 Amazon CloudWatch User Guide XRayTransactionSearchConfig: Type: AWS::XRay::TransactionSearchConfig Properties: IndexingPercentage: 50 JSON { "Resources": { "XRayTransactionSearchConfig": { "Type": "AWS::XRay::TransactionSearchConfig", "Properties": { "IndexingPercentage": 20 } } } } The IndexingPercentage value can be set between 0 and 100. Template examples The following example includes both the resource policy and the TransactionSearchConfig. YAML Resources: LogsResourcePolicy: Type: AWS::Logs::ResourcePolicy Properties: PolicyName: TransactionSearchAccess PolicyDocument: !Sub > { "Version": "2012-10-17", "Statement": [ { "Sid": "TransactionSearchXRayAccess", "Effect": "Allow", "Principal": { "Service": "xray.amazonaws.com" }, "Action": "logs:PutLogEvents", Getting started with Transaction Search 1600 Amazon CloudWatch "Resource": [ User Guide "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log- group:aws/spans:*", "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log- group:/aws/application-signals/data:*" ], "Condition": { "ArnLike": { "aws:SourceArn": "arn:${AWS::Partition}:xray:${AWS::Region}: ${AWS::AccountId}:*" }, "StringEquals": { "aws:SourceAccount": "${AWS::AccountId}" } } } ] } XRayTransactionSearchConfig: Type: AWS::XRay::TransactionSearchConfig Properties: IndexingPercentage: 10 JSON { "Resources": { "LogsResourcePolicy": { "Type": "AWS::Logs::ResourcePolicy", "Properties": { "PolicyName": "TransactionSearchAccess", "PolicyDocument": { "Fn::Sub": "{\n \"Version\": \"2012-10-17\",\n \"Statement \": [\n {\n \"Sid\": \"TransactionSearchXRayAccess\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"xray.amazonaws.com\"\n },\n \"Action\": \"logs:PutLogEvents\",\n \"Resource\": [\n \"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:aws/spans:* \",\n \"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log- group:/aws/application-signals/data:*\"\n ],\n \"Condition\": {\n \"ArnLike\": {\n \"aws:SourceArn\": \"arn:${AWS::Partition}:xray: ${AWS::Region}:${AWS::AccountId}:*\"\n },\n \"StringEquals\": {\n \"aws:SourceAccount\": \"${AWS::AccountId}\"\n }\n }\n }\n ]\n}" Getting started with Transaction Search 1601 User Guide Amazon CloudWatch } } }, "XRayTransactionSearchConfig": { "Type": "AWS::XRay::TransactionSearchConfig", "Properties": { "IndexingPercentage": 20 } } } } Here is an example using AWS CDK in TypeScript. CDK import * as cdk from '@aws-cdk/core'; import * as logs from '@aws-cdk/aws-logs'; import * as xray from '@aws-cdk/aws-xray'; export class XRayTransactionSearchStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // Create the resource policy const transactionSearchAccess = new logs.CfnResourcePolicy(this, 'XRayLogResourcePolicy', { policyName: 'TransactionSearchAccess', policyDocument: JSON.stringify({ Version: '2012-10-17', Statement: [ { Sid: 'TransactionSearchXRayAccess', Effect: 'Allow', Principal: { Service: 'xray.amazonaws.com', }, Action: 'logs:PutLogEvents', Resource: [ `arn:${this.partition}:logs:${this.region}:${this.account}:log-group:aws/ spans:*`, `arn:${this.partition}:logs:${this.region}:${this.account}:log-group:/ aws/application-signals/data:*`, ], Getting started with Transaction Search 1602 Amazon CloudWatch Condition: { User Guide ArnLike: { 'aws:SourceArn': `arn:${this.partition}:xray:${this.region}: ${this.account}:*`, }, StringEquals: { 'aws:SourceAccount': this.account, }, }, }, ], }), }); // Create the TransactionSearchConfig with dependency const transactionSearchConfig = new xray.CfnTransactionSearchConfig(this, 'XRayTransactionSearchConfig', { indexingPercentage: 10, }); // Add the dependency to ensure Resource Policy is created first transactionSearchConfig.addDependsOn(transactionSearchAccess); } } Verifying the configuration After deploying your AWS CloudFormation stack, you can verify the configuration using the AWS CLI. aws xray get-trace-segment-destination A successful configuration will return the following. { "Destination": "CloudWatchLogs", "Status": "ACTIVE" } Getting started with Transaction Search 1603 Amazon CloudWatch Spans User Guide Spans sent to X-Ray are ingested and managed in a log group called aws/spans. This topic describes which CloudWatch Logs features are available for transaction spans. Available features The following CloudWatch Logs features are available for transaction spans. • Metric filters – Use metric filters to extract custom metrics from spans. • Subscriptions – Use subscriptions to access a real-time feed of span events from CloudWatch Logs. • Log anomaly detection – Use log anomaly detection to establish a baseline for spans sent to the aws/spans log group. • Contributor Insights – Use Contributor Insights to analyze span data and create a time series displaying contributor data. Unsupported features The following are features not supported for transaction spans. • Spans cannot be sent to CloudWatch Logs with the PutLogEvents API. • Span data cannot be enriched or transformed. Note Span ingestion is charged separately from log ingestion. For information about pricing, see Amazon CloudWatch Pricing. Searching and analyzing spans Transaction Search provides you with a visual editor to search and analyze all ingested spans using attributes. You can use the visual editor to narrow down transaction spans and create interactive visualizations to troubleshoot issues in your distributed applications. You can also use the CloudWatch Logs Insights query language to analyze your spans. This topic describes how to access and use the visual editor. Spans 1604 Amazon CloudWatch The visual editor User Guide The following procedure describes how to access the visual editor. To access the visual editor 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. From the navigation pane, choose Application Signals, and then choose Transaction Search. Use span attributes, such as service name, span duration, and span status to narrow down transaction spans quickly. You can access these filters and more on the right side of the visual editor under Select filters. This visual editor suggests a list of attributes in the span. These attributes include attributes added through auto-instrumentation and custom attributes added through custom instrumentation. Select a span key, and enter a value to refine span results. You can filter spans using various operations, such as "Equals," "Does Not Equal," and more. Spans 1605 Amazon
acw-ug-430
acw-ug.pdf
430
pane, choose Application Signals, and then choose Transaction Search. Use span attributes, such as service name, span duration, and span status to narrow down transaction spans quickly. You can access these filters and more on the right side of the visual editor under Select filters. This visual editor suggests a list of attributes in the span. These attributes include attributes added through auto-instrumentation and custom attributes added through custom instrumentation. Select a span key, and enter a value to refine span results. You can filter spans using various operations, such as "Equals," "Does Not Equal," and more. Spans 1605 Amazon CloudWatch User Guide Query formats You can run queries in the visual editor using different formats. This section describes each of these formats. List View spans or span events in a list format, which displays information about each span. Use this type of analysis to analyze individual spans, understand specific transactions, or identify unique patterns in transaction events. Other use cases include the following: Use cases • Troubleshoot customer support tickets • Locate APIs or dependencies, such as database queries taking longer than 1000 milliseconds to execute • Locate spans with errors The following screenshots show how to troubleshoot a customer support ticket with this type of analysis. Spans 1606 Amazon CloudWatch Example scenario User Guide In the visual editor, filter on all transaction spans with a particular customer issue. Before you run your query, choose List from the Visualize as dropdown. The results show a list of spans where you can choose a trace ID to get the end-to-end journey for the transaction and determine the root cause of the issue. Spans 1607 Amazon CloudWatch User Guide Timeseries View spans or span events over time. Use this type of analysis to look at trends and spikes in transaction activity. Other use cases include the following: • Visualize latency • Visualize frequency of spans • Visualize performance The following screenshots show how you can view p99 latency trends for an API with this type of analysis. Example scenario In the visual editor, filter on the service and API you want to analyze. Spans 1608 Amazon CloudWatch User Guide Before you run your query, choose Time series from the Visualize as dropdown. Choose P99 for the duration statistic from the Show span as dropdown. The results show a latency trend for the service, with the x-axis of the graph being time and y-axis being p99 duration. You can choose a point on the chart to view correlated spans and span events. Spans 1609 Amazon CloudWatch User Guide Group analysis Aggregate spans or span events based on specific attributes, such as account IDs and status codes, to display statistical metrics. Use this type of analysis to analyze spans in clusters, compare different groups, and uncover trends at the macro level. Other use cases include the following: Use cases • Identify top customers impacted by a service outage • Identify availability zones with the most errors • Identify the top slowest database queries The following screenshots show how you can view the top customers impacted by a service outage with this type of analysis. Example scenario In the visual editor, you filter on the service experiencing issues. Spans 1610 Amazon CloudWatch User Guide Before you run your query, choose Group Analysis from the Visualize as dropdown. Group your query results by account.id, and limit the number of results to 10.. The results show the top 10 customers who experienced the most number of errors. CloudWatch Logs Insights You can use CloudWatch Logs Insights to analyze your spans. Spans 1611 Amazon CloudWatch Example query User Guide The following query shows the top five slowest database queries. STATS pct(durationNano, 99) as `p99` by attributes.db.statement | SORT p99 ASC | LIMIT 5 | DISPLAY p99,attributes.db.statement Example query The following query shows which top five services are throwing errors. FILTER `attributes.http.response.status_code` >= 500 | STATS count(*) as `count` by attributes.aws.local.service as service | SORT count ASC | LIMIT 5 | DISPLAY count,service Ingesting spans for complete visibility Recording all transaction spans provides comprehensive visibility into application issues. It enables you to debug customer support tickets or troubleshoot rarely occurring p99 API latency spikes, which is crucial when identifying the root cause of issues in customer-facing and mission-critical applications. You can create a cost-effective strategy to start capturing 100% of trace spans in CloudWatch by configuring the head sampling rate and then adjusting a lower span indexing rate. Setting up head sampling Head sampling is a tracing technique capturing requests at the beginning of a trace, which is based on a set rate or condition. When the head sampling rate is set to 100%, it captures the beginning of every trace without skips, guaranteeing complete visibility into all incoming requests, and that no transaction data is missed. You
acw-ug-431
acw-ug.pdf
431
identifying the root cause of issues in customer-facing and mission-critical applications. You can create a cost-effective strategy to start capturing 100% of trace spans in CloudWatch by configuring the head sampling rate and then adjusting a lower span indexing rate. Setting up head sampling Head sampling is a tracing technique capturing requests at the beginning of a trace, which is based on a set rate or condition. When the head sampling rate is set to 100%, it captures the beginning of every trace without skips, guaranteeing complete visibility into all incoming requests, and that no transaction data is missed. You can configure head sampling if you're using X-Ray or AWS Distro for OpenTelemetry SDKs or the OpenTelemetry SDK. Spans 1612 Amazon CloudWatch User Guide If you're using X-Ray or AWS Distro for OpenTelemetry SDKs Navigate to your sampling rules in the console, and set the fixed sampling rate to 100%. This guarantees all trace spans are captured and ingested into CloudWatch logs. For more information, see Configuring sampling rules If you're using the OpenTelemetry SDK To record 100% of spans and get complete visibility, set your sampling configuration to always_on. For more information, see Language APIs & SDKs on the OpenTelemetry website. Features unlocked with head sampling When you enable Transaction Search, all spans collected from your application through head sampling are ingested as structured logs in CloudWatch. This provides you with the following features: • The ability to search span attributes and analyze span events in a visual editor. • The ability to visualize traces containing up to 10,000 spans. • Total support for OpenTelemetry, which includes the ability to embed business events into spans for analysis and use span links to define connections between traces for end-to-end viewing. • Access to application dashboards, metrics, and topology with CloudWatch Application Signals enabled for all spans sent to CloudWatch. Note Because spans are available in a log group called aws/spans, you can use CloudWatch Logs features with transaction spans. For more information, see The span log group. Setting up span indexing with trace summaries Trace summaries can help you debug transactions and are beneficial for asynchronous processes. You only need to index a small percentage of spans as trace summaries. You configure span indexing when you enable Transaction Search in the console or with the API. To enable Transaction Search, see Getting started with Transaction Search. Spans 1613 Amazon CloudWatch User Guide Features unlocked with trace summaries The key features of X-Ray trace summaries include the following: • Trace summary search – Search and find traces from trace summaries. • Trace summary analytics – Interpret trace data. • Trace insights – Analyze trace data to identify application issues. Monitoring spans across accounts Spans sent to X-Ray are ingested and managed in a log group called aws/spans. To monitor spans across multiple accounts, you must enable Transaction Search across all source and monitoring accounts and enable cross-account observability for logs and traces. When you enable cross- account observability, you can search up to 10,000 accounts and get visibility into traces across accounts. This feature is provided at no extra cost for the aws/spans log group. If you enable cross-account observability for trace summaries, the first trace summary copy is free. For more information about pricing, see Amazon CloudWatch Pricing. Adding custom attributes CloudWatch Application Signals utilizes OpenTelemetry to auto-instrument your applications and collect spans from popular libraries in different languages, such as Java, Python, and more. Auto-instrumentation captures information, such as database queries, HTTP requests, cache accesses, and external service calls, which allows you to troubleshoot application performance issues. You can add custom instrumentation to enrich spans with business-specific data or other information you wish to capture. This data can be recorded as a custom attribute or a span event, providing insights tailored to your troubleshooting needs. Note For information about adding custom attributes or span events in a different language, see Language APIs and SDKS in the OpenTelemetry website. Adding custom attributes 1614 Amazon CloudWatch Custom attributes User Guide You can add business related attributes or any other attributes to your spans in all languages OpenTelemetry supports. The following is a Java code snippet that adds an order id and customer details to a span. import io.opentelemetry.api.trace.Span; public class OrderProcessor { public void processOrder() { Span span = Span.current(); span.setAttribute("order.id", "123456"); span.setAttribute("customer.name", "John Doe"); span.setAttribute("customer.id", "4343dfdd"); // Your order processing logic here System.out.println("Order processed with custom attributes"); } } After these attributes have been added to the span, they become available to search and analyze in the Transaction Search visual editor. Span events A span event is typically used to denote a meaningful, singular point in time during a span duration. Exceptions are auto-captured as span events through auto-instrumentation, but you can also add custom business events, such as payment-status
acw-ug-432
acw-ug.pdf
432
customer details to a span. import io.opentelemetry.api.trace.Span; public class OrderProcessor { public void processOrder() { Span span = Span.current(); span.setAttribute("order.id", "123456"); span.setAttribute("customer.name", "John Doe"); span.setAttribute("customer.id", "4343dfdd"); // Your order processing logic here System.out.println("Order processed with custom attributes"); } } After these attributes have been added to the span, they become available to search and analyze in the Transaction Search visual editor. Span events A span event is typically used to denote a meaningful, singular point in time during a span duration. Exceptions are auto-captured as span events through auto-instrumentation, but you can also add custom business events, such as payment-status or cart-abandonment. For more information, see Span events on the OpenTelemetry website. You can embed span events to your spans in all the languages CloudWatch Application Signals and OpenTelemetry support. The following is a Java code snippet of adding a custom event to a span. import io.opentelemetry.api.trace.Span; public class OrderProcessor { public void bookOrder() { Span span = Span.current(); Adding custom attributes 1615 Amazon CloudWatch User Guide // Add a booking started event span.addEvent("booking started"); // Add a payment succeeded event or failed event span.addEvent("booking failed"); } } Prerequisites for the CloudWatch agent When using the CloudWatch agent to emit span events to X-Ray, you must turn on the `transit_spans_in_otlp_format` flag in your configuration. { "traces": { ... "transit_spans_in_otlp_format": true ... } } After you add these events, they become available in the Transaction Search visual editor. CloudWatch Logs queries You can query span events in CloudWatch Logs to view advanced insights. The following example query commands show how to analyze exceptions thrown by your application: fields jsonparse(@message) as js | unnest js.events into event | filter event.name = "exception" | display event.attributes.`exception.stacktrace` fields jsonparse(@message) as js | unnest js.events into event | filter event.name = "exception" | stats count() by event.attributes.`exception.type` Adding custom attributes 1616 Amazon CloudWatch User Guide Troubleshooting application issues With Application Signals, you can troubleshoot rarely occurring latency spikes in your applications. After you enable Transaction Search and configure a head sampling rate capturing 100% of spans, you get complete visibility into any application issue. The following scenario describes how Application Signals can be used with transaction spans to monitor your services and identify service quality issues. Example troubleshooting scenario This scenario focuses on a pet clinic application composed of several micro-services calling third- party payment APIs. These calls have been intermittently slow, thus impacting revenue. Jane opens the CloudWatch Application Signals console and notices a customer-service application responsible for registering customers is healthy and not breaching any SLOs. She opens the service to investigate any patterns of rarely occurring failures and notices the registration API experienced intermittent p99 latency spikes. Jane chooses a datapoint in the latency chart to view correlated spans. She groups the spans by customer ID to view all the customers who are impacted by the latency spikes. Troubleshooting application issues 1617 Amazon CloudWatch User Guide Jane selects one of the correlated spans with a fault status, which opens the trace detail page for the selected trace. She scrolls to the segments timeline section to follow the call path, where she notices that calls to the payment gateway have been failing and preventing customers from registering. Troubleshooting application issues 1618 Amazon CloudWatch User Guide Synthetic monitoring (canaries) You can use Amazon CloudWatch Synthetics to create canaries, configurable scripts that run on a schedule, to monitor your endpoints and APIs. Canaries follow the same routes and perform the same actions as a customer, which makes it possible for you to continually verify your customer experience even when you don't have any customer traffic on your applications. By using canaries, you can discover issues before your customers do. Canaries are scripts written in Node.js or Python. They create Lambda functions in your account that use Node.js or Python as a framework. Canaries work over both HTTP and HTTPS protocols. Canaries use Lambda layers that contain the CloudWatch Synthetics library. The library contains the NodeJS version of CloudWatch Synthetics for NodeJS canaries and the Python version of CloudWatch Synthetics for Python canaries. The layers belong to the CloudWatch Synthetics service account. Libraries never transmit or store customer information. All customer data is stored in the customer account only. Canaries offer programmatic access to a headless Google Chrome Browser via Puppeteer or Selenium Webdriver. For more information about Puppeteer, see Puppeteer. For more information about Selenium, see www.selenium.dev/. Canaries check the availability and latency of your endpoints and can store load time data and screenshots of the UI. They monitor your REST APIs, URLs, and website content, and they can check for unauthorized changes from phishing, code injection and cross-site scripting. CloudWatch Synthetics is integrated with Application Signals, which can discover and monitor your application services, clients, Synthetics canaries, and service dependencies. Use Application Synthetic monitoring
acw-ug-433
acw-ug.pdf
433
customer account only. Canaries offer programmatic access to a headless Google Chrome Browser via Puppeteer or Selenium Webdriver. For more information about Puppeteer, see Puppeteer. For more information about Selenium, see www.selenium.dev/. Canaries check the availability and latency of your endpoints and can store load time data and screenshots of the UI. They monitor your REST APIs, URLs, and website content, and they can check for unauthorized changes from phishing, code injection and cross-site scripting. CloudWatch Synthetics is integrated with Application Signals, which can discover and monitor your application services, clients, Synthetics canaries, and service dependencies. Use Application Synthetic monitoring (canaries) 1619 Amazon CloudWatch User Guide Signals to see a list or visual map of your services, view health metrics based on your service level objectives (SLOs), and drill down to see correlated X-Ray traces for more detailed troubleshooting. To see your canaries in Application Signals, turn on X-Ray active tracing. Your canaries are displayed on the Service Map connected to your services, and in the Service detail page of the services they call. For a video demonstration of canaries, see the following: • Introduction to Amazon CloudWatch Synthetics • Amazon CloudWatch Synthetics Demo • Create Canaries Using Amazon CloudWatch Synthetics • Visual Monitoring with Amazon CloudWatch Synthetics You can run a canary once or on a regular schedule. Canaries can run as often as once per minute. You can use both cron and rate expressions to schedule canaries. For information about security issues to consider before you create and run canaries, see Security considerations for Synthetics canaries. By default, canaries create several CloudWatch metrics in the CloudWatchSynthetics namespace. These metrics have CanaryName as a dimension. Canaries that use the executeStep() or executeHttpStep() function from the function library also have StepName as a dimension. For more information about the canary function library, see Library functions available for canary scripts. CloudWatch Synthetics integrates well with the X-Ray Trace Map, which uses CloudWatch with AWS X-Ray to provide an end-to-end view of your services to help you more efficiently pinpoint performance bottlenecks and identify impacted users. Canaries that you create with CloudWatch Synthetics appear on the trace map. For more information, see X-Ray Trace Map. CloudWatch Synthetics is currently available in all commercial AWS Regions and the GovCloud Regions. Note In Asia Pacific (Osaka), AWS PrivateLink is not supported. In Asia Pacific (Jakarta), AWS PrivateLink and X-Ray are not supported. Synthetic monitoring (canaries) 1620 Amazon CloudWatch Topics • Required roles and permissions for CloudWatch canaries User Guide • Creating a canary • Groups • Test a canary locally • Troubleshooting a failed canary • Sample code for canary scripts • Canaries and X-Ray tracing • Running a canary on a VPC • Encrypting canary artifacts • Viewing canary statistics and details • CloudWatch metrics published by canaries • Edit or delete a canary • Start, stop, delete, or update runtime for multiple canaries • Monitoring canary events with Amazon EventBridge • Performing safe canary updates Required roles and permissions for CloudWatch canaries Both the users who create and manage canaries, and the canaries themselves, must have certain permissions. Required roles and permissions for users who manage CloudWatch canaries To view canary details and the results of canary runs, you must be signed in as a user with either the CloudWatchSyntheticsFullAccess or the CloudWatchSyntheticsReadOnlyAccess policies attached. To read all Synthetics data in the console, you also need the AmazonS3ReadOnlyAccess and CloudWatchReadOnlyAccess policies. To view the source code used by canaries, you also need the AWSLambda_ReadOnlyAccess policy. To create canaries, you must be signed in as an user who has the CloudWatchSyntheticsFullAccess policy or a similar set of permissions. To create IAM roles for the canaries, you also need the following inline policy statement: Required roles and permissions 1621 Amazon CloudWatch User Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "iam:CreateRole", "iam:CreatePolicy", "iam:AttachRolePolicy" ], "Resource": [ "arn:aws:iam::*:role/service-role/CloudWatchSyntheticsRole*", "arn:aws:iam::*:policy/service-role/CloudWatchSyntheticsPolicy*" ] } ] } Important Granting a user the iam:CreateRole, iam:CreatePolicy, and iam:AttachRolePolicy permissions gives that user full administrative access to your AWS account. For example, a user with these permissions can create a policy that has full permissions for all resources and can attach that policy to any role. Be very careful about who you grant these permissions to. For information about attaching policies and granting permissions to users, see Changing Permissions for an IAM User and To embed an inline policy for a user or role. Required roles and permissions for canaries Each canary must be associated with an IAM role that has certain permissions attached. When you create a canary using the CloudWatch console, you can choose for CloudWatch Synthetics to create an IAM role for the canary. If you do, the role will have the permissions needed. If you want to create the IAM role yourself, or create an
acw-ug-434
acw-ug.pdf
434
about who you grant these permissions to. For information about attaching policies and granting permissions to users, see Changing Permissions for an IAM User and To embed an inline policy for a user or role. Required roles and permissions for canaries Each canary must be associated with an IAM role that has certain permissions attached. When you create a canary using the CloudWatch console, you can choose for CloudWatch Synthetics to create an IAM role for the canary. If you do, the role will have the permissions needed. If you want to create the IAM role yourself, or create an IAM role that you can use when using the AWS CLI or APIs to create a canary, the role must contain the permissions listed in this section. All IAM roles for canaries must include the following trust policy statement. Required roles and permissions 1622 Amazon CloudWatch User Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Additionally, the canary's IAM role needs one of the following statements. Basic canary that doesn't use AWS KMS or need Amazon VPC access { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject" ], "Resource": [ "arn:aws:s3:::path/to/your/s3/bucket/canary/results/folder" ] }, { "Effect": "Allow", "Action": [ "s3:GetBucketLocation" ], "Resource": [ "arn:aws:s3:::name/of/the/s3/bucket/that/contains/canary/results" ] }, { "Effect": "Allow", "Action": [ Required roles and permissions 1623 Amazon CloudWatch User Guide "logs:CreateLogStream", "logs:PutLogEvents", "logs:CreateLogGroup" ], "Resource": [ "arn:aws:logs:canary_region_name:canary_account_id:log-group:/aws/ lambda/cwsyn-canary_name-*" ] }, { "Effect": "Allow", "Action": [ "s3:ListAllMyBuckets", "xray:PutTraceSegments" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Resource": "*", "Action": "cloudwatch:PutMetricData", "Condition": { "StringEquals": { "cloudwatch:namespace": "CloudWatchSynthetics" } } } ] } Canary that uses AWS KMS to encrypt canary artifacts but does not need Amazon VPC access { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject" ], "Resource": [ Required roles and permissions 1624 Amazon CloudWatch User Guide "arn:aws:s3:::path/to/your/S3/bucket/canary/results/folder" ] }, { "Effect": "Allow", "Action": [ "s3:GetBucketLocation" ], "Resource": [ "arn:aws:s3:::name/of/the/S3/bucket/that/contains/canary/results" ] }, { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents", "logs:CreateLogGroup" ], "Resource": [ "arn:aws:logs:canary_region_name:canary_account_id:log-group:/aws/ lambda/cwsyn-canary_name-*" ] }, { "Effect": "Allow", "Action": [ "s3:ListAllMyBuckets", "xray:PutTraceSegments" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Resource": "*", "Action": "cloudwatch:PutMetricData", "Condition": { "StringEquals": { "cloudwatch:namespace": "CloudWatchSynthetics" } } }, Required roles and permissions 1625 Amazon CloudWatch { "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": User Guide "arn:aws:kms:KMS_key_region_name:KMS_key_account_id:key/KMS_key_id", "Condition": { "StringEquals": { "kms:ViaService": [ "s3.region_name_of_the_canary_results_S3_bucket.amazonaws.com" ] } } } ] } Canary that does not use AWS KMS but does need Amazon VPC access { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject" ], "Resource": [ "arn:aws:s3:::path/to/your/S3/bucket/canary/results/folder" ] }, { "Effect": "Allow", "Action": [ "s3:GetBucketLocation" ], "Resource": [ "arn:aws:s3:::name/of/the/S3/bucket/that/contains/canary/results" ] }, { Required roles and permissions 1626 Amazon CloudWatch User Guide "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents", "logs:CreateLogGroup" ], "Resource": [ "arn:aws:logs:canary_region_name:canary_account_id:log-group:/aws/ lambda/cwsyn-canary_name-*" ] }, { "Effect": "Allow", "Action": [ "s3:ListAllMyBuckets", "xray:PutTraceSegments" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Resource": "*", "Action": "cloudwatch:PutMetricData", "Condition": { "StringEquals": { "cloudwatch:namespace": "CloudWatchSynthetics" } } }, { "Effect": "Allow", "Action": [ "ec2:CreateNetworkInterface", "ec2:DescribeNetworkInterfaces", "ec2:DeleteNetworkInterface" ], "Resource": [ "*" ] } ] Required roles and permissions 1627 Amazon CloudWatch } User Guide Canary that uses AWS KMS to encrypt canary artifacts and also needs Amazon VPC access If you update a non-VPC canary to start using a VPC, you'll need to update the canary's role to include the network interface permissions listed in the following policy. { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject" ], "Resource": [ "arn:aws:s3:::path/to/your/S3/bucket/canary/results/folder" ] }, { "Effect": "Allow", "Action": [ "s3:GetBucketLocation" ], "Resource": [ "arn:aws:s3:::name/of/the/S3/bucket/that/contains/canary/results" ] }, { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents", "logs:CreateLogGroup" ], "Resource": [ "arn:aws:logs:canary_region_name:canary_account_id:log-group:/aws/ lambda/cwsyn-canary_name-*" ] }, { "Effect": "Allow", "Action": [ Required roles and permissions 1628 Amazon CloudWatch User Guide "s3:ListAllMyBuckets", "xray:PutTraceSegments" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Resource": "*", "Action": "cloudwatch:PutMetricData", "Condition": { "StringEquals": { "cloudwatch:namespace": "CloudWatchSynthetics" } } }, { "Effect": "Allow", "Action": [ "ec2:CreateNetworkInterface", "ec2:DescribeNetworkInterfaces", "ec2:DeleteNetworkInterface" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "arn:aws:kms:KMS_key_region_name:KMS_key_account_id:key/KMS_key_id", "Condition": { "StringEquals": { "kms:ViaService": [ "s3.region_name_of_the_canary_results_S3_bucket.amazonaws.com" ] } } } Required roles and permissions 1629 Amazon CloudWatch ] } User Guide AWS managed policies for CloudWatch Synthetics To add permissions to users, groups, and roles, it is easier to use AWS managed policies than to write policies yourself. It takes time and expertise to create IAM customer managed policies that provide your team with only the permissions they need. To get started quickly, you can use our AWS managed policies. These policies cover common use cases and are available in your AWS account. For more information about AWS managed policies, see AWS managed policies AWS managed policies in the IAM User Guide. AWS services maintain and update AWS managed policies. You can't change the permissions
acw-ug-435
acw-ug.pdf
435
CloudWatch Synthetics To add permissions to users, groups, and roles, it is easier to use AWS managed policies than to write policies yourself. It takes time and expertise to create IAM customer managed policies that provide your team with only the permissions they need. To get started quickly, you can use our AWS managed policies. These policies cover common use cases and are available in your AWS account. For more information about AWS managed policies, see AWS managed policies AWS managed policies in the IAM User Guide. AWS services maintain and update AWS managed policies. You can't change the permissions in AWS managed policies. Services occasionally change the permissions in an AWS managed policy. This type of update affects all identities (users, groups, and roles) where the policy is attached. CloudWatch Synthetics updates to AWS managed policies View details about updates to AWS managed policies for CloudWatch Synthetics since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the CloudWatch Document history page. Change Description Date Redundant actions removed from CloudWatchSyntheti csFullAccess CloudWatch Synthetics March 12, 2021 removed the s3:PutBuc ketEncryption and lambda:GetLayerVer sionByArn actions from CloudWatchSyntheti csFullAccess policy because those actions were redundant with other permissions in the policy. The removed actions did not provide any permissio ns, and there’s no net change to the permissions granted by the policy. Required roles and permissions 1630 Amazon CloudWatch User Guide Change Description Date CloudWatch Synthetics started tracking changes CloudWatch Synthetics started tracking changes for its AWS managed policies. March 10, 2021 CloudWatchSyntheticsFullAccess Here are the contents of the CloudWatchSyntheticsFullAccess policy: { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "synthetics:*" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "s3:CreateBucket", "s3:PutEncryptionConfiguration" ], "Resource": [ "arn:aws:s3:::cw-syn-results-*" ] }, { "Effect": "Allow", "Action": [ "iam:ListRoles", "s3:ListAllMyBuckets", "xray:GetTraceSummaries", "xray:BatchGetTraces", "apigateway:GET" ], "Resource": "*" }, { "Effect": "Allow", Required roles and permissions 1631 Amazon CloudWatch User Guide "Action": [ "s3:GetBucketLocation" ], "Resource": "arn:aws:s3:::*" }, { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:ListBucket" ], "Resource": "arn:aws:s3:::cw-syn-*" }, { "Effect": "Allow", "Action": [ "s3:GetObjectVersion" ], "Resource": "arn:aws:s3:::aws-synthetics-library-*" }, { "Effect": "Allow", "Action": [ "iam:PassRole" ], "Resource": [ "arn:aws:iam::*:role/service-role/CloudWatchSyntheticsRole*" ], "Condition": { "StringEquals": { "iam:PassedToService": [ "lambda.amazonaws.com", "synthetics.amazonaws.com" ] } } }, { "Effect": "Allow", "Action": [ "iam:GetRole", "iam:ListAttachedRolePolicies" ], "Resource": [ Required roles and permissions 1632 Amazon CloudWatch User Guide "arn:aws:iam::*:role/service-role/CloudWatchSyntheticsRole*" ] }, { "Effect": "Allow", "Action": [ "cloudwatch:GetMetricData", "cloudwatch:GetMetricStatistics" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "cloudwatch:PutMetricAlarm", "cloudwatch:DeleteAlarms" ], "Resource": [ "arn:aws:cloudwatch:*:*:alarm:Synthetics-*" ] }, { "Effect": "Allow", "Action": [ "cloudwatch:DescribeAlarms" ], "Resource": [ "arn:aws:cloudwatch:*:*:alarm:*" ] }, { "Effect": "Allow", "Action": [ "logs:GetLogRecord", "logs:DescribeLogStreams", "logs:StartQuery", "logs:GetLogEvents", "logs:FilterLogEvents", "logs:GetLogGroupFields" ], "Resource": [ "arn:aws:logs:*:*:log-group:/aws/lambda/cwsyn-*" ], "Condition": { Required roles and permissions 1633 Amazon CloudWatch User Guide "StringEquals": { "aws:ResourceAccount": "${aws:PrincipalAccount}" } } }, { "Effect": "Allow", "Action": [ "lambda:CreateFunction", "lambda:AddPermission", "lambda:PublishVersion", "lambda:UpdateFunctionCode", "lambda:UpdateFunctionConfiguration", "lambda:GetFunctionConfiguration", "lambda:GetFunction", "lambda:DeleteFunction", "lambda:ListTags", "lambda:TagResource", "lambda:UntagResource" ], "Resource": [ "arn:aws:lambda:*:*:function:cwsyn-*" ] }, { "Effect": "Allow", "Action": [ "lambda:GetLayerVersion", "lambda:PublishLayerVersion", "lambda:DeleteLayerVersion" ], "Resource": [ "arn:aws:lambda:*:*:layer:cwsyn-*", "arn:aws:lambda:*:*:layer:Synthetics:*", "arn:aws:lambda:*:*:layer:Synthetics_Selenium:*", "arn:aws:lambda:*:*:layer:AWS-CW-Synthetics*:*" ] }, { "Effect": "Allow", "Action": [ "ec2:DescribeVpcs", "ec2:DescribeSubnets", "ec2:DescribeSecurityGroups" Required roles and permissions 1634 User Guide Amazon CloudWatch ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "sns:ListTopics" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "sns:CreateTopic", "sns:Subscribe", "sns:ListSubscriptionsByTopic" ], "Resource": [ "arn:*:sns:*:*:Synthetics-*" ] }, { "Effect": "Allow", "Action": [ "kms:ListAliases" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "kms:DescribeKey" ], "Resource": "arn:aws:kms:*:*:key/*" }, { "Effect": "Allow", "Action": [ "kms:Decrypt" ], Required roles and permissions 1635 Amazon CloudWatch User Guide "Resource": "arn:aws:kms:*:*:key/*", "Condition": { "StringLike": { "kms:ViaService": [ "s3.*.amazonaws.com" ] } } } ] } CloudWatchSyntheticsReadOnlyAccess Here are the contents of the CloudWatchSyntheticsReadOnlyAccess policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "synthetics:Describe*", "synthetics:Get*", "synthetics:List*" ], "Resource": "*" } ] } Limiting a user to viewing specific canaries You can limit a user's ability to view information about canaries, so that they can only see information about the canaries you specify. To do this, use an IAM policy with a Condition statement similar to the following, and attach this policy to a user or an IAM role. The following example limits the user to only viewing information about name-of-allowed- canary-1 and name-of-allowed-canary-2. { Required roles and permissions 1636 Amazon CloudWatch User Guide "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "synthetics:DescribeCanaries", "Resource": "*", "Condition": { "ForAnyValue:StringEquals": { "synthetics:Names": [ "name-of-allowed-canary-1", "name-of-allowed-canary-2" ] } } } ] } CloudWatch Synthetics supports listing as many as five items in the synthetics:Names array. You can also create a policy that uses a * as a wildcard in canary names that are to be allowed, as in the following example: { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "synthetics:DescribeCanaries", "Resource": "*", "Condition": { "ForAnyValue:StringLike": { "synthetics:Names": [ "my-team-canary-*"
acw-ug-436
acw-ug.pdf
436
about name-of-allowed- canary-1 and name-of-allowed-canary-2. { Required roles and permissions 1636 Amazon CloudWatch User Guide "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "synthetics:DescribeCanaries", "Resource": "*", "Condition": { "ForAnyValue:StringEquals": { "synthetics:Names": [ "name-of-allowed-canary-1", "name-of-allowed-canary-2" ] } } } ] } CloudWatch Synthetics supports listing as many as five items in the synthetics:Names array. You can also create a policy that uses a * as a wildcard in canary names that are to be allowed, as in the following example: { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "synthetics:DescribeCanaries", "Resource": "*", "Condition": { "ForAnyValue:StringLike": { "synthetics:Names": [ "my-team-canary-*" ] } } } ] } Required roles and permissions 1637 Amazon CloudWatch User Guide Any user signed in with one of these policies attached can't use the CloudWatch console to view any canary information. They can view canary information only for the canaries authorized by the policy and only by using the DescribeCanaries API or the describe-canaries AWS CLI command. Creating a canary Important Ensure that you use Synthetics canaries to monitor only endpoints and APIs where you have ownership or permissions. Depending on the canary frequency settings, these endpoints might experience increased traffic. When you use the CloudWatch console to create a canary, you can use a blueprint provided by CloudWatch to create your canary or you can write your own script. For more information, see Using canary blueprints. You can also create a canary using AWS CloudFormation if you are using your own script for the canary. For more information, see AWS::Synthetics::Canary in the AWS CloudFormation User Guide. If you are writing your own script, you can use several functions that CloudWatch Synthetics has built into a library. For more information, see Synthetics runtime versions. Note When you create a canary, one of the layers created is a Synthetics layer prepended with Synthetics. This layer is owned by the Synthetics service account and contains the runtime code. To create a canary 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Application Signals, Synthetics Canaries. 3. Choose Create Canary. 4. Choose one of the following: Creating a canary 1638 Amazon CloudWatch User Guide • To base your canary on a blueprint script, choose Use a blueprint, and then choose the type of canary you want to create. For more information about what each type of blueprint does, see Using canary blueprints. • To upload your own Node.js script to create a custom canary, choose Upload a script. You can then drag your script into the Script area or choose Browse files to navigate to the script in your file system. • To import your script from an S3 bucket, choose Import from S3. Under Source location, enter the complete path to your canary or choose Browse S3. You must have s3:GetObject and s3:GetObjectVersion permissions for the S3 bucket that you use. The bucket must be in the same AWS Region where you are creating the canary. 5. Under Name, enter a name for your canary. The name is used on many pages, so we recommend that you give it a descriptive name that distinguishes it from other canaries. 6. Under Application or endpoint URL, enter the URL that you want the canary to test. This URL must include the protocol (such as https://). If you want the canary to test an endpoint on a VPC, you must also enter information about your VPC later in this procedure. 7. If you are using your own script for the canary, under Lambda handler, enter the entry point where you want the canary to start. If you use a runtime earlier than syn-nodejs- puppeteer-3.4 or syn-python-selenium-1.1, the string that you enter must end with .handler. If you use syn-nodejs-puppeteer-3.4 or syn-python-selenium-1.1 or a later runtime, this restriction does not apply. 8. If you are using environment variables in your script, choose Environment variables and then specify a value for each environment variable defined in your script. For more information, see Environment variables. 9. Under Schedule, choose whether to run this canary just once, run it continuously using a rate expression, or schedule it using a cron expression. • When you use the CloudWatch console to create a canary that runs continuously, you can choose a rate anywhere between once a minute and once an hour. Creating a canary 1639 Amazon CloudWatch User Guide • For more information about writing a cron expression for canary scheduling, see Scheduling canary runs using cron. 10. (Optional) To set a timeout value for the canary, choose Additional configuration and then specify the timeout value. Make it no shorter than 15 seconds to allow for Lambda cold starts and the time it takes to boot up the canary instrumentation. 11. Under Data retention, specify how long to retain information about both failed
acw-ug-437
acw-ug.pdf
437
canary that runs continuously, you can choose a rate anywhere between once a minute and once an hour. Creating a canary 1639 Amazon CloudWatch User Guide • For more information about writing a cron expression for canary scheduling, see Scheduling canary runs using cron. 10. (Optional) To set a timeout value for the canary, choose Additional configuration and then specify the timeout value. Make it no shorter than 15 seconds to allow for Lambda cold starts and the time it takes to boot up the canary instrumentation. 11. Under Data retention, specify how long to retain information about both failed and successful canary runs. The range is 1-455 days. This setting affects the range of information returned by GetCanaryRuns operations, as well as the range of information displayed in the Synthetics console. It does not affect the data stored in your Amazon S3 buckets, or logs or metrics that are published by the canary. Regardless of the canary's data retention period, the range of information displayed in console has certain limits. In the Synthetics console home view, the relative and absolute time range are limited to seven days. In the Synthetics console view for a specific canary, the relative time range is limited to seven days and the absolute time range is limited to 30 days. 12. Under Data Storage, select the S3 bucket to use to store the data from the canary runs. The bucket name can't contain a period (.). If you leave this blank, a default S3 bucket is used or created. If you are using the syn-nodejs-puppeteer-3.0 or later runtime, when you enter the URL for the bucket in the text box, you can specify a bucket in the current Region or in a different Region. If you are using an earlier runtime version, the bucket must be in the current Region. 13. (Optional) By default, canaries store their artifacts on Amazon S3, and the artifacts are encrypted at rest using an AWS-managed AWS KMS key. You can use a different encryption option by choosing Additional configuration in the Data Storage section. You can then choose the type of key to use for encryption. For more information, see Encrypting canary artifacts. 14. Under Access permissions, choose whether to create an IAM role to run the canary or use an existing one. If you have CloudWatch Synthetics create the role, it automatically includes all the necessary permissions. If you want to create the role yourself, see Required roles and permissions for canaries for information about the necessary permissions. Creating a canary 1640 Amazon CloudWatch User Guide If you use the CloudWatch console to create a role for a canary when you create the canary, you can't re-use the role for other canaries, because these roles are specific to just one canary. If you have manually created a role that works for multiple canaries, you can use that existing role. To use an existing role, you must have the iam:PassRole permission to pass that role to Synthetics and Lambda. You must also have the iam:GetRole permission. 15. (Optional) Under Alarms, choose whether you want default CloudWatch alarms to be created for this canary. If you choose to create alarms, they are created with the following name convention:Synthetics-Alarm-canaryName-index index is a number representing each different alarm created for this canary. The first alarm has an index of 1, the second alarm has an index of 2, and so on. 16. (Optional) To have this canary test an endpoint that is on a VPC, choose VPC settings, and then do the following: a. b. c. d. Select the VPC that hosts the endpoint. Select one or more subnets on your VPC. You must select a private subnet because a Lambda instance can't be configured to run in a public subnet when an IP address can't be assigned to the Lambda instance during execution. For more information, see Configuring a Lambda Function to Access Resources in a VPC. Select one or more security groups on your VPC. To allow outbound IPv6 traffic for this canary, select Allow IPv6 Traffic for dual-stack subnets. This enables the canary to monitor IPv6-only and dual stack enabled endpoints over IPv6. You can monitor endpoints external to your VPC by giving the canary internet access and configuring the VPC subnets appropriately. For more information, see Running a canary on a VPC. If the endpoint is on a VPC, you must enable your canary to send information to CloudWatch and Amazon S3. For more information, see Running a canary on a VPC. 17. (Optional) Under Tags, add one or more key-value pairs as tags for this canary. Tags can help you identify and organize your AWS resources and track your AWS costs. For more information, see Tagging your Amazon CloudWatch resources. Creating a canary 1641 Amazon CloudWatch
acw-ug-438
acw-ug.pdf
438
to your VPC by giving the canary internet access and configuring the VPC subnets appropriately. For more information, see Running a canary on a VPC. If the endpoint is on a VPC, you must enable your canary to send information to CloudWatch and Amazon S3. For more information, see Running a canary on a VPC. 17. (Optional) Under Tags, add one or more key-value pairs as tags for this canary. Tags can help you identify and organize your AWS resources and track your AWS costs. For more information, see Tagging your Amazon CloudWatch resources. Creating a canary 1641 Amazon CloudWatch User Guide If you want the tags that you apply to the canary to also be applied to the Lambda function that the canary uses, choose Lambda function under Tag Replication. If you choose this option, CloudWatch Synthetics will keep the tags on the canary and the Lambda function synchronized: • Synthetics will apply the same tags that you specify here to both your canary and your Lambda function. • If you later update the canary's tags and keep this option selected, Synthetics modifies the tags on your Lambda function to remain in sync with the canary. 18. (Optional) Under Active tracing, choose whether to enable active X-Ray tracing for this canary. This option is available only if the canary uses runtime version syn-nodejs-2.0 or later. Active tracing is only available for Puppeteer runtimes. For more information, see Canaries and X-Ray tracing. Resources that are created for canaries When you create a canary, the following resources are created: • An IAM role with the name CloudWatchSyntheticsRole-canary-name-uuid (if you use CloudWatch console to create the canary and specify for a new role to be created for the canary) • An IAM policy with the name CloudWatchSyntheticsPolicy-canary-name-uuid. • An S3 bucket with the name cw-syn-results-accountID-region. • Alarms with the name Synthetics-Alarm-MyCanaryName, if you want alarms to be created for the canary. • Lambda functions and layers, if you use a blueprint to create the canary. These resources have the prefix cwsyn-MyCanaryName. • CloudWatch Logs log groups with the name /aws/lambda/cwsyn-MyCanaryName-randomId. Using canary blueprints This section provides details about each of the canary blueprints and the tasks each blueprint is best suited for. Blueprints are provided for the following canary types: • Heartbeat Monitor • API Canary Creating a canary 1642 Amazon CloudWatch • Broken Link Checker • Visual Monitoring • Canary Recorder • GUI Workflow User Guide When you use a blueprint to create a canary, as you fill out the fields in the CloudWatch console, the Script editor area of the page displays the canary you are creating as a Node.js script. You can also edit your canary in this area to customize it further. Heartbeat monitoring Heartbeat scripts load the specified URL and store a screenshot of the page and an HTTP archive file (HAR file). They also store logs of accessed URLs. You can use the HAR files to view detailed performance data about the web pages. You can analyze the list of web requests and catch performance issues such as time to load for an item. If your canary uses the syn-nodejs-puppeteer-3.1 or later runtime version, you can use the heartbeat monitoring blueprint to monitor multiple URLs and see the status, duration, associated screenshots, and failure reason for each URL in the step summary of the canary run report. API canary API canaries can test the basic Read and Write functions of a REST API. REST stands for representational state transfer and is a set of rules that developers follow when creating an API. One of these rules states that a link to a specific URL should return a piece of data. Canaries can work with any APIs and test all types of functionality. Each canary can make multiple API calls. In canaries that use runtime version syn-nodejs-2.2 or later, the API canary blueprint supports multi-step canaries that monitor your APIs as HTTP steps. You can test multiple APIs in a single canary. Each step is a separate request that can access a different URL, use different headers, and use different rules for whether headers and response bodies are captured. By not capturing headers and response body, you can prevent sensitive data from being recorded. Each request in an API canary consists of the following information: • The endpoint, which is the URL that you request. Creating a canary 1643 Amazon CloudWatch User Guide • The method, which is the type of request that is sent to the server. REST APIs support GET (read), POST (write), PUT (update), PATCH (update), and DELETE (delete) operations. • The headers, which provide information to both the client and the server. They are used for authentication and providing information about the body content. For a list of valid headers, see HTTP Headers.
acw-ug-439
acw-ug.pdf
439
can prevent sensitive data from being recorded. Each request in an API canary consists of the following information: • The endpoint, which is the URL that you request. Creating a canary 1643 Amazon CloudWatch User Guide • The method, which is the type of request that is sent to the server. REST APIs support GET (read), POST (write), PUT (update), PATCH (update), and DELETE (delete) operations. • The headers, which provide information to both the client and the server. They are used for authentication and providing information about the body content. For a list of valid headers, see HTTP Headers. • The data (or body), which contains information to be sent to the server. This is used only for POST, PUT, PATCH, or DELETE requests. Note API canary blueprints are not supported by Playwright runtimes. The API canary blueprint supports GET and POST methods. When you use this blueprint, you must specify headers. For example, you can specify Authorization as a Key and specify the necessary authorization data as the Value for that key. If you are testing a POST request, you also specify the content to post in the Data field. Integration with API Gateway The API blueprint is integrated with Amazon API Gateway. This enables you to select an API Gateway API and stage from the same AWS account and Region as the canary, or to upload a Swagger template from API Gateway for cross-account and cross-Region API monitoring. You can then choose the rest of the details in the console to create the canary, instead of entering them from scratch. For more information about API Gateway, see What is Amazon API Gateway? Using a private API You can create a canary that uses a private API in Amazon API Gateway. For more information, see Creating a private API in Amazon API Gateway? Broken link checker The broken link checker collects all the links inside the URL that you are testing by using document.getElementsByTagName('a'). It tests only up to the number of links that you specify, and the URL itself is counted as the first link. For example, if you want to check all the links on a page that contains five links, you must specify for the canary to follow six links. Creating a canary 1644 Amazon CloudWatch User Guide Broken link checker canaries created using the syn-nodejs-2.0-beta runtime or later support the following additional features: • Provides a report that includes the links that were checked, status code, failure reason (if any), and source and destination page screenshots. • When viewing canary results, you can filter to see only the broken links and then fix the link based on the reason for failure. • This version captures annotated source page screenshots for each link and highlights the anchor where the link was found. Hidden components are not annotated. • You can configure this version to capture screenshots of both source and destination pages, just source pages, or just destination pages. • This version fixes an issue in the earlier version where the canary script stops after the first broken link even when more links are scraped from the first page. Note Broken link checker blueprints are not supported by Playwright runtimes. To update an existing canary using syn-1.0 to use the new runtime, you must delete and re- create the canary. Updating an existing canary to the new runtime does not make these features available. A broken link checker canary detects the following types of link errors: • 404 Page Not Found • Invalid Host Name • Bad URL. For example, the URL is missing a bracket, has extra slashes, or uses the wrong protocol. • Invalid HTTP response code. • The host server returns empty responses with no content and no response code. • The HTTP requests constantly time out during the canary's run. • The host consistently drops connections because it is misconfigured or is too busy. Creating a canary 1645 Amazon CloudWatch Visual monitoring blueprint User Guide The visual monitoring blueprint includes code to compare screenshots taken during a canary run with screenshots taken during a baseline canary run. If the discrepancy between the two screenshots is beyond a threshold percentage, the canary fails. Visual monitoring is supported in canaries running syn-puppeteer-node-3.2 and later. It is not currently supported in canaries running Python and Selenium, or using Playwright runtimes. The visual monitoring blueprint includes the following line of code in the default blueprint canary script, which enables visual monitoring. syntheticsConfiguration.withVisualCompareWithBaseRun(true); The first time that the canary runs successfully after this line is added to the script, it uses the screenshots taken during that run as the baseline for comparison. After that first canary run, you can use the CloudWatch console to edit the canary to do any of the following: • Set the
acw-ug-440
acw-ug.pdf
440
fails. Visual monitoring is supported in canaries running syn-puppeteer-node-3.2 and later. It is not currently supported in canaries running Python and Selenium, or using Playwright runtimes. The visual monitoring blueprint includes the following line of code in the default blueprint canary script, which enables visual monitoring. syntheticsConfiguration.withVisualCompareWithBaseRun(true); The first time that the canary runs successfully after this line is added to the script, it uses the screenshots taken during that run as the baseline for comparison. After that first canary run, you can use the CloudWatch console to edit the canary to do any of the following: • Set the next run of the canary as the new baseline. • Draw boundaries on the current baseline screenshot to designate areas of the screenshot to ignore during visual comparisons. • Remove a screenshot from being used for visual monitoring. For more information about using the CloudWatch console to edit a canary, see Edit or delete a canary. You can also change the canary run that is used as the baseline by using the nextrun or lastrun parameters or specifing a canary run ID in the UpdateCanary API. When you use the visual monitoring blueprint, you enter the URL where you want the screenshot to be taken, and specify a difference threshold as a percentage. After the baseline run, future runs of the canary that detect a visual difference greater than that threshold trigger a canary failure. After the baseline run, you can also edit the canary to "draw" boundaries on the baseline screenshot that you want to ignore during the visual monitoring. The visual monitoring feature is powered by the the ImageMagick open source software toolkit. For more information, see ImageMagick . Creating a canary 1646 Amazon CloudWatch Canary recorder User Guide With the canary recorder blueprint, you can use the CloudWatch Synthetics Recorder to record your click and type actions on a website and automatically generate a Node.js script that can be used to create a canary that follows the same steps. The CloudWatch Synthetics Recorder is a Google Chrome extension provided by Amazon. The canary recorder is not supported for canaries that use the Playwright runtime. Credits: The CloudWatch Synthetics Recorder is based on the Headless recorder . For more information, see Using the CloudWatch Synthetics Recorder for Google Chrome. GUI workflow builder The GUI Workflow Builder blueprint verifies that actions can be taken on your webpage. For example, if you have a webpage with a login form, the canary can populate the user and password fields and submit the form to verify that the webpage is working correctly. When you use a blueprint to create this type of canary, you specify the actions that you want the canary to take on the webpage. The actions that you can use are the following: • Click— Selects the element that you specify and simulates a user clicking or choosing the element. To specify the element in a Node.js script, use [id=] or a[class=]. To specify the element in a Python script, use xpath //*[@id=] or //*[@class=]. • Verify selector— Verifies that the specified element exists on the webpage. This test is useful for verifying that a previous action has causes the correct elements to populate the page. To specify the element to verify in a Node.js script, use [id=] or a[class=]. To specify the element to verify in a Python script, use xpath //*[@id=] or //*[class=]. • Verify text— Verifies that the specified string is contained within the target element. This test is useful for verifying that a previous action has caused the correct text to be displayed. To specify the element in a Node.js script, use a format such as div[@id=]//h1 because this action uses the waitForXPath function in Puppeteer. To specify the element in a Python script, use xpath format such as //*[@id=] or //*[@class=] because this action uses the implicitly_wait function in Selenium. Creating a canary 1647 Amazon CloudWatch User Guide • Input text— Writes the specified text in the target element. To specify the element to verify in a Node.js script, use [id=] or a[class=]. To specify the element to verify in a Python script, use xpath //*[@id=] or //*[@class=]. • Click with navigation— Waits for the whole page to load after choosing the specified element. This is most useful when you need to reload the page. To specify the element in a Node.js script, use [id=] or a[class=]. To specify the element in a Python script, use xpath //*[@id=] or //*[@class=]. For example, the following blueprint uses Node.js. It clicks the firstButton on the specified URL, verifies that the expected selector with the expected text appears, inputs the name Test_Customer into the Name field, clicks the Login button, and then verifies that the login is successful by checking for the Welcome text on the next
acw-ug-441
acw-ug.pdf
441
the whole page to load after choosing the specified element. This is most useful when you need to reload the page. To specify the element in a Node.js script, use [id=] or a[class=]. To specify the element in a Python script, use xpath //*[@id=] or //*[@class=]. For example, the following blueprint uses Node.js. It clicks the firstButton on the specified URL, verifies that the expected selector with the expected text appears, inputs the name Test_Customer into the Name field, clicks the Login button, and then verifies that the login is successful by checking for the Welcome text on the next page. Creating a canary 1648 Amazon CloudWatch User Guide GUI workflow canaries that use the following runtimes also provide a summary of the steps executed for each canary run. You can use the screenshots and error message associated with each step to find the root cause of failure. • syn-nodejs-2.0 or later • syn-python-selenium-1.0 or later Using the CloudWatch Synthetics Recorder for Google Chrome Amazon provides a CloudWatch Synthetics Recorder to help you create canaries more easily. The recorder is a Google Chrome extension. The recorder records your click and type actions on a website and automatically generates a Node.js script that can be used to create a canary that follows the same steps. After you start recording, the CloudWatch Synthetics Recorder detects your actions in the browser and converts them to a script. You can pause and resume the recording as needed. When you stop recording, the recorder produces a Node.js script of your actions, which you can easily copy with the Copy to Clipboard button. You can then use this script to create a canary in CloudWatch Synthetics. Credits: The CloudWatch Synthetics Recorder is based on the Headless recorder . Installing the CloudWatch Synthetics Recorder extension for Google Chrome To use the CloudWatch Synthetics Recorder, you can start creating a canary and choose the Canary Recorder blueprint. If you do this when you haven't already downloaded the recorder, the CloudWatch Synthetics console provides a link to download it. Alternatively, you can follow these steps to download and install the recorder directly. To install the CloudWatch Synthetics Recorder 1. Using Google Chrome, go to this website: https://chrome.google.com/webstore/detail/ cloudwatch-synthetics-rec/bhdnlmmgiplmbcdmkkdfplenecpegfno 2. Choose Add to Chrome, then choose Add extension. Creating a canary 1649 Amazon CloudWatch User Guide Using the CloudWatch Synthetics Recorder for Google Chrome To use the CloudWatch Synthetics Recorder to help you create a canary, you can choose Create canary in the CloudWatch console, and then choose Use a blueprint, Canary Recorder. For more information, see Creating a canary. Alternatively, you can use the recorder to record steps without immediately using them to create a canary. To use the CloudWatch Synthetics Recorder to record your actions on a website 1. Navigate to the page that you want to monitor. 2. Choose the Chrome extensions icon, and then choose CloudWatch Synthetics Recorder. 3. Choose Start Recording. 4. Perform the steps that you want to record. To pause recording, choose Pause. 5. When you are finished recording the workflow, choose Stop recording. 6. Choose Copy to clipboard to copy the generated script to your clipboard. Or, if you want to start over, choose New recording. 7. To create a canary with the copied script, you can paste your copied script into the recorder blueprint inline editor, or save it to an Amazon S3 bucket and import it from there. 8. If you're not immediately creating a canary, you can save your recorded script to a file. Known limitations of the CloudWatch Synthetics Recorder The CloudWatch Synthetics Recorder for Google Chrome currently has the following limitations. • HTML elements that don’t have IDs will use CSS selectors. This can break canaries if the webpage structure changes later. We plan to provide some configuration options (such as using data-id) around this in a future version of the recorder. • The recorder doesn't support actions such as double-click or copy/paste, and doesn't support key combinations such as CMD+0. • To verify the presence of an element or text on the page, users must add assertions after the script is generated. The recorder doesn't support verifying an element without performing any action on that element. This is similar to the “Verify text” or “Verify element” options in the canary workflow builder. We plan to add some assertions support in a future version of the recorder. Creating a canary 1650 Amazon CloudWatch User Guide • The recorder records all actions in the tab where the recording is initiated. It doesn't record pop- ups (for instance, to allow location tracking) or navigation to different pages from pop-ups. Synthetics runtime versions When you create or update a canary, you choose a Synthetics runtime version for the canary. A Synthetics runtime is a combination of the Synthetics code that
acw-ug-442
acw-ug.pdf
442
This is similar to the “Verify text” or “Verify element” options in the canary workflow builder. We plan to add some assertions support in a future version of the recorder. Creating a canary 1650 Amazon CloudWatch User Guide • The recorder records all actions in the tab where the recording is initiated. It doesn't record pop- ups (for instance, to allow location tracking) or navigation to different pages from pop-ups. Synthetics runtime versions When you create or update a canary, you choose a Synthetics runtime version for the canary. A Synthetics runtime is a combination of the Synthetics code that calls your script handler, and the Lambda layers of bundled dependencies. CloudWatch Synthetics currently supports runtimes that use Node.js for scripts and the Puppeteer framework, and runtimes that use Python for scripting and Selenium Webdriver for the framework. We recommend that you always use the most recent runtime version for your canaries, to be able to use the latest features and updates made to the Synthetics library. When you create a canary, one of the layers created is a Synthetics layer prefixed with Synthetics. This layer is owned by the Synthetics service account and contains the runtime code. Note Whenever you a canary to use a new version of the Synthetics runtime, all Synthetics library functions that your canary uses are also automatically u to the same version of NodeJS that the Synthetics runtime supports. Topics • CloudWatch Synthetics runtime support policy • Runtime versions using Node.js and Playwright • Runtime versions using Node.js and Puppeteer • Runtime versions using Python and Selenium Webdriver CloudWatch Synthetics runtime support policy Synthetics runtime versions are subject to maintenance and security updates. When any component of a runtime version is no longer supported, that Synthetics runtime version is deprecated. Creating a canary 1651 Amazon CloudWatch User Guide You can't create canaries using deprecated runtime versions. Canaries that use deprecated runtimes continue to run. You can stop, start, and delete these canaries. You can update an existing canary that uses a deprecated runtime version by updating the canary to use a supported runtime version. CloudWatch Synthetics notifies you by email if you have canaries that use runtimes that are scheduled to be deprecated in the next 60 days. We recommend that you migrate your canaries to a supported runtime version to benefit from the new functionality, security, and performance enhancements that are included in more recent releases. How do I update a canary to a new runtime version? You can update a canary’s runtime version by using the CloudWatch console, AWS CloudFormation, the AWS CLI or the AWS SDK. When you use the CloudWatch console, you can update up to five canaries at once by selecting them in the canary list page and then choosing Actions, Update Runtime. You can verify the update by first testing your update before committing the runtime update. When updating the runtime versions, choose the Start Dry Run or Validate and save later options in the CloudWatch console to create a dry run of the original canary along with any changes you made to the configuration. The dry run will update and execute the canary to validate whether the runtime update is safe for the canary. Once you have verified your canary with the new runtime version, you can update the runtime version of your canary. For more information, see Performing safe canary updates. Alternatively, you can verify the update by first cloning the canary using the CloudWatch console and updating the runtime version. This creates another canary which is a clone of your original canary. Once you have verified your canary with the new runtime version, you can update the runtime version of your original canary and delete the clone canary. You can also update multiple canaries using an upgrade script. For more information, see Canary runtime upgrade script. If you upgrade a canary and it fails, see Troubleshooting a failed canary. CloudWatch Synthetics runtime deprecation dates The following table lists the date of deprecation of each deprecated CloudWatch Synthetics runtime. Creating a canary 1652 Amazon CloudWatch User Guide Runtime Version Deprecation date syn-nodejs- puppeteer-7.0 syn-nodejs- puppeteer-6.2 syn-nodejs- puppeteer-5.2 syn-python- selenium-3.0 syn-python- selenium-2.1 syn-nodejs- puppeteer-6.1 syn-nodejs- puppeteer-6.0 syn-nodejs- puppeteer-5.1 syn-nodejs- puppeteer-5.0 syn-nodejs- puppeteer-4.0 syn-nodejs- puppeteer-3.9 syn-nodejs- puppeteer-3.8 October 1, 2025 October 1, 2025 October 1, 2025 October 1, 2025 October 1, 2025 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 January 8, 2024 January 8, 2024 Creating a canary 1653 Amazon CloudWatch User Guide Runtime Version Deprecation date syn-python- selenium-2.0 syn-python- selenium-1.3 syn-python- selenium-1.2 syn-python- selenium-1.1 syn-python- selenium-1.0 syn-nodejs- puppeteer-3.7 syn-nodejs- puppeteer-3.6 syn-nodejs- puppeteer-3.5 syn-nodejs- puppeteer-3.4 syn-nodejs- puppeteer-3.3 syn-nodejs- puppeteer-3.2 syn-nodejs- puppeteer-3.1 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 January 8, 2024 January
acw-ug-443
acw-ug.pdf
443
puppeteer-5.1 syn-nodejs- puppeteer-5.0 syn-nodejs- puppeteer-4.0 syn-nodejs- puppeteer-3.9 syn-nodejs- puppeteer-3.8 October 1, 2025 October 1, 2025 October 1, 2025 October 1, 2025 October 1, 2025 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 January 8, 2024 January 8, 2024 Creating a canary 1653 Amazon CloudWatch User Guide Runtime Version Deprecation date syn-python- selenium-2.0 syn-python- selenium-1.3 syn-python- selenium-1.2 syn-python- selenium-1.1 syn-python- selenium-1.0 syn-nodejs- puppeteer-3.7 syn-nodejs- puppeteer-3.6 syn-nodejs- puppeteer-3.5 syn-nodejs- puppeteer-3.4 syn-nodejs- puppeteer-3.3 syn-nodejs- puppeteer-3.2 syn-nodejs- puppeteer-3.1 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 March 8, 2024 January 8, 2024 January 8, 2024 January 8, 2024 November 13, 2022 November 13, 2022 November 13, 2022 November 13, 2022 Creating a canary 1654 Amazon CloudWatch User Guide Runtime Version Deprecation date syn-nodejs- puppeteer-3.0 November 13, 2022 syn-nodejs-2.2 May 28, 2021 syn-nodejs-2.1 May 28, 2021 syn-nodejs-2.0 May 28, 2021 syn-nodejs-2.0- February 8, 2021 beta syn-1.0 May 28, 2021 Canary runtime upgrade script To upgrade a canary script to a supported runtime version, use the following script. const AWS = require('aws-sdk'); // You need to configure your AWS credentials and Region. // https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting- credentials-node.html // https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting- region.html const synthetics = new AWS.Synthetics(); const DEFAULT_OPTIONS = { /** * The number of canaries to upgrade during a single run of this script. */ count: 10, /** * No canaries are upgraded unless force is specified. */ force: false }; Creating a canary 1655 Amazon CloudWatch /** * The number of milliseconds to sleep between GetCanary calls when * verifying that an update succeeded. User Guide */ const SLEEP_TIME = 5000; (async () => { try { const options = getOptions(); const versions = await getRuntimeVersions(); const canaries = await getAllCanaries(); const upgrades = canaries .filter(canary => !versions.isLatestVersion(canary.RuntimeVersion)) .map(canary => { return { Name: canary.Name, FromVersion: canary.RuntimeVersion, ToVersion: versions.getLatestVersion(canary.RuntimeVersion) }; }); if (options.force) { const promises = []; for (const upgrade of upgrades.slice(0, options.count)) { const promise = upgradeCanary(upgrade); promises.push(promise); // Sleep for 100 milliseconds to avoid throttling. await usleep(100); } const succeeded = []; const failed = []; for (let i = 0; i < upgrades.slice(0, options.count).length; i++) { const upgrade = upgrades[i]; const promise = promises[i]; try { await promise; console.log(`The update of ${upgrade.Name} succeeded.`); succeeded.push(upgrade.Name); } catch (e) { console.log(`The update of ${upgrade.Name} failed with error: ${e}`); failed.push({ Creating a canary 1656 Amazon CloudWatch User Guide Name: upgrade.Name, Reason: e }); } } if (succeeded.length) { console.group('The following canaries were upgraded successfully.'); for (const name of succeeded) { console.log(name); } console.groupEnd() } else { console.log('No canaries were upgraded successfully.'); } if (failed.length) { console.group('The following canaries were not upgraded successfully.'); for (const failure of failed) { console.log('\x1b[31m', `${failure.Name}: ${failure.Reason}`, '\x1b[0m'); } console.groupEnd(); } } else { console.log('Run with --force [--count <count>] to perform the first <count> upgrades shown. The default value of <count> is 10.') console.table(upgrades); } } catch (e) { console.error(e); } })(); function getOptions() { const force = getFlag('--force', DEFAULT_OPTIONS.force); const count = getOption('--count', DEFAULT_OPTIONS.count); return { force, count }; function getFlag(key, defaultValue) { return process.argv.includes(key) || defaultValue; } function getOption(key, defaultValue) { const index = process.argv.indexOf(key); if (index < 0) { Creating a canary 1657 Amazon CloudWatch User Guide return defaultValue; } const value = process.argv[index + 1]; if (typeof value === 'undefined' || value.startsWith('-')) { throw `The ${key} option requires a value.`; } return value; } } function getAllCanaries() { return new Promise((resolve, reject) => { const canaries = []; synthetics.describeCanaries().eachPage((err, data) => { if (err) { reject(err); } else { if (data === null) { resolve(canaries); } else { canaries.push(...data.Canaries); } } }); }); } function getRuntimeVersions() { return new Promise((resolve, reject) => { const jsVersions = []; const pythonVersions = []; synthetics.describeRuntimeVersions().eachPage((err, data) => { if (err) { reject(err); } else { if (data === null) { jsVersions.sort((a, b) => a.ReleaseDate - b.ReleaseDate); pythonVersions.sort((a, b) => a.ReleaseDate - b.ReleaseDate); resolve({ isLatestVersion(version) { const latest = this.getLatestVersion(version); return latest === version; }, Creating a canary 1658 Amazon CloudWatch User Guide getLatestVersion(version) { if (jsVersions.some(v => v.VersionName === version)) { return jsVersions[jsVersions.length - 1].VersionName; } else if (pythonVersions.some(v => v.VersionName === version)) { return pythonVersions[pythonVersions.length - 1].VersionName; } else { throw Error(`Unknown version ${version}`); } } }); } else { for (const version of data.RuntimeVersions) { if (version.VersionName === 'syn-1.0') { jsVersions.push(version); } else if (version.VersionName.startsWith('syn-nodejs-2.')) { jsVersions.push(version); } else if (version.VersionName.startsWith('syn-nodejs-puppeteer-')) { jsVersions.push(version); } else if (version.VersionName.startsWith('syn-python-selenium-')) { pythonVersions.push(version); } else { throw Error(`Unknown version ${version.VersionName}`); } } } } }); }); } async function upgradeCanary(upgrade) { console.log(`Upgrading canary ${upgrade.Name} from ${upgrade.FromVersion} to ${upgrade.ToVersion}`); await synthetics.updateCanary({ Name: upgrade.Name, RuntimeVersion: upgrade.ToVersion }).promise(); while (true) { await usleep(SLEEP_TIME); console.log(`Getting the state of canary ${upgrade.Name}`); const response = await synthetics.getCanary({ Name: upgrade.Name }).promise(); const state = response.Canary.Status.State; console.log(`The state of canary ${upgrade.Name} is ${state}`); if (state === 'ERROR' || response.Canary.Status.StateReason) {
acw-ug-444
acw-ug.pdf
444
{ for (const version of data.RuntimeVersions) { if (version.VersionName === 'syn-1.0') { jsVersions.push(version); } else if (version.VersionName.startsWith('syn-nodejs-2.')) { jsVersions.push(version); } else if (version.VersionName.startsWith('syn-nodejs-puppeteer-')) { jsVersions.push(version); } else if (version.VersionName.startsWith('syn-python-selenium-')) { pythonVersions.push(version); } else { throw Error(`Unknown version ${version.VersionName}`); } } } } }); }); } async function upgradeCanary(upgrade) { console.log(`Upgrading canary ${upgrade.Name} from ${upgrade.FromVersion} to ${upgrade.ToVersion}`); await synthetics.updateCanary({ Name: upgrade.Name, RuntimeVersion: upgrade.ToVersion }).promise(); while (true) { await usleep(SLEEP_TIME); console.log(`Getting the state of canary ${upgrade.Name}`); const response = await synthetics.getCanary({ Name: upgrade.Name }).promise(); const state = response.Canary.Status.State; console.log(`The state of canary ${upgrade.Name} is ${state}`); if (state === 'ERROR' || response.Canary.Status.StateReason) { throw response.Canary.Status.StateReason; } Creating a canary 1659 Amazon CloudWatch User Guide if (state !== 'UPDATING') { return; } } } function usleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } Runtime versions using Node.js and Playwright The following sections contain information about the CloudWatch Synthetics runtime versions for Node.js and Playwright. Playwright is an open-source automation library for browser testing. For more information about Playwright, see https://playwright.dev/ The naming convention for these runtime versions is syn-language-framework-majorversion.minorversion. syn-nodejs-playwright-2.0 Major dependencies: • AWS Lambda runtime Node.js 20.x • Playwright version 1.49.1 • Playwright/test version 1.49.1 • Chromium version 131.0.6778.264 Changes in syn-nodejs-playwright-2.0 • The mismatch between total duration and sum of timings for a given request in HAR file is fixed. • Supports dry runs for the canary which allows for adhoc executions or performing a safe canary update. Previous runtime versions for Node.js and Playwright The following earlier runtime versions for Node.js and Playwright are still supported. Creating a canary 1660 User Guide Amazon CloudWatch syn-nodejs-playwright-1.0 Major dependencies: • AWS Lambda runtime Node.js 20.x • Playwright version 1.44.1 • Playwright/test version 1.44.1 • Chromium version 126.0.6478.126 Features: • PlayWright support – You can write canary scripts by using the Playwright automation framework. You can bring your existing Playwright scripts to run as canaries, and enhance them with AWS monitoring capabilities. • CloudWatch Logs integration – You can query and filter for logs through the CloudWatch Synthetics console. Each log message contains unique canaryRunId, making it easy to search for logs for a particular canary run. • Metrics and canary artifacts – You can monitor canary run pass rate through CloudWatch metrics, and configure alarms to alert you when canaries detect issues. • Screenshots and steps association – You can capture screenshots using native Playwright functionality to visualize the stages of a canary script on each run. Screenshots are automatically associated with canary steps, and are uploaded to Amazon S3 buckets. • Multiple tabs– You can create canaries that open multiple browser tabs, and access screenshots from each tab. You can create multi-tab and multi-step user workflows in Synthetics. Runtime versions using Node.js and Puppeteer The first runtime version for Node.js and Puppeteer was named syn-1.0. Later runtime versions have the naming convention syn-language-majorversion.minorversion. Starting with syn-nodejs-puppeteer-3.0, the naming convention is syn-language-framework-majorversion.minorversion An additional -beta suffix shows that the runtime version is currently in a beta preview release. Runtime versions with the same major version number are backward compatible. Creating a canary 1661 Amazon CloudWatch Important User Guide IMPORTANT: The included AWS SDK for JavaScript v2 dependency will be removed and updated to use AWS SDK for JavaScript v3 in a future runtime release. When that happens, you can update your canary code references. Alternatively, you can continue referencing and using the included AWS SDK for JavaScript v2 dependency by adding it as a dependency to your source code zip file. The Lambda code in a canary is configured to have a maximum memory of 1 GB. Each run of a canary times out after a configured timeout value. If no timeout value is specified for a canary, CloudWatch chooses a timeout value based on the canary's frequency. If you configure a timeout value, make it no shorter than 15 seconds to allow for Lambda cold starts and the time it takes to boot up the canary instrumentation. Notes for all runtime versions When using syn-nodejs-puppeteer-3.0 runtime version, make sure that your canary script is compatible with Node.js 12.x. If you use an earlier version of a syn-nodejs runtime version, make sure that that your script is compatible with Node.js 10.x. syn-nodejs-puppeteer-10.0 syn-nodejs-puppeteer-10.0 is the most recent Synthetics runtime for Node.js and Puppeteer. Important Lambda Node.js 18 and later runtimes use AWS SDK for JavaScript V3. If you need to migrate a function from an earlier runtime, follow the aws-sdk-js-v3 Migration Workshop on GitHub. For more information about AWS SDK for JavaScript version 3, see this blog post. Major dependencies: • Lambda runtime Node.js 20.x • Puppeteer-core version 24.2.0 • Chromium version 131.0.6778.264 Creating a canary 1662 Amazon CloudWatch User Guide Changes in syn-nodejs-puppeteer-10.0 • The bug related to closing the browser that took excessively long is fixed. • Supports dry runs
acw-ug-445
acw-ug.pdf
445
syn-nodejs-puppeteer-10.0 is the most recent Synthetics runtime for Node.js and Puppeteer. Important Lambda Node.js 18 and later runtimes use AWS SDK for JavaScript V3. If you need to migrate a function from an earlier runtime, follow the aws-sdk-js-v3 Migration Workshop on GitHub. For more information about AWS SDK for JavaScript version 3, see this blog post. Major dependencies: • Lambda runtime Node.js 20.x • Puppeteer-core version 24.2.0 • Chromium version 131.0.6778.264 Creating a canary 1662 Amazon CloudWatch User Guide Changes in syn-nodejs-puppeteer-10.0 • The bug related to closing the browser that took excessively long is fixed. • Supports dry runs for the canary which allows for adhoc executions or performing a safe canary update. Previous runtime versions for Node.js and Puppeteer The following earlier runtime versions for Node.js and Puppeteer are still supported. syn-nodejs-puppeteer-9.1 syn-nodejs-puppeteer-9.1 is the most recent Synthetics runtime for Node.js and Puppeteer. Important Lambda Node.js 18 and later runtimes use AWS SDK for JavaScript V3. If you need to migrate a function from an earlier runtime, follow the aws-sdk-js-v3 Migration Workshop on GitHub. For more information about AWS SDK for JavaScript version 3, see this blog post. Major dependencies: • Lambda runtime Node.js 20.x • Puppeteer-core version 22.12.1 • Chromium version 126.0.6478.126 Changes in syn-nodejs-puppeteer-9.1 – Bug fixes related to date ranges and pending requests in HAR files are fixed. syn-nodejs-puppeteer-9.0 Important Lambda Node.js 18 and later runtimes use AWS SDK for JavaScript V3. If you need to migrate a function from an earlier runtime, follow the aws-sdk-js-v3 Migration Workshop Creating a canary 1663 Amazon CloudWatch User Guide on GitHub. For more information about AWS SDK for JavaScript version 3, see this blog post. Major dependencies: • Lambda runtime Node.js 20.x • Puppeteer-core version 22.12.1 • Chromium version 126.0.6478.126 Changes in syn-nodejs-puppeteer-9.0 – The bug fix to enable visual monitoring capabilities is fixed. syn-nodejs-puppeteer-8.0 Warning Because of a bug, the syn-nodejs-puppeteer-8.0 runtime doesn't support visual monitoring in canaries. Upgrade to syn-nodejs-puppeteer-9.0 for the bug fix for visual monitoring. Important Lambda Node.js 18 and later runtimes use AWS SDK for JavaScript V3. If you need to migrate a function from an earlier runtime, follow the aws-sdk-js-v3 Migration Workshop on GitHub. For more information about AWS SDK for JavaScript version 3, see this blog post. Major dependencies: • Lambda runtime Node.js 20.x • Puppeteer-core version 22.10.0 • Chromium version 125.0.6422.112 Updates in syn-nodejs-puppeteer-8.0: Creating a canary 1664 Amazon CloudWatch User Guide • Support for two-factor authentication • Bug fixes related to some service clients losing data in Node.js SDK V3 responses is fixed. syn-nodejs-puppeteer-7.0 Major dependencies: • Lambda runtime Node.js 18.x • Puppeteer-core version 21.9.0 • Chromium version 121.0.6167.139 Code size: The size of code and dependencies that you can package into this runtime is 80 MB. Updates in syn-nodejs-puppeteer-7.0: • Updated versions of the bundled libraries in Puppeteer and Chromium— The Puppeteer and Chromium dependencies are updated to new versions. Important Moving from Puppeteer 19.7.0 to Puppeteer 21.9.0 introduces breaking changes regarding testing and filters. For more information, see the BREAKING CHANGES sections in puppeteer: v20.0.0 and puppeteer-core: v21.0.0. Recommended upgrade to AWS SDK v3 The Lambda nodejs18.x runtime doesn't support AWS SDK v2. We strongly recommend that you migrate to AWS SDK v3. syn-nodejs-puppeteer-6.2 Major dependencies: • Lambda runtime Node.js 18.x • Puppeteer-core version 19.7.0 Creating a canary 1665 Amazon CloudWatch User Guide • Chromium version 111.0.5563.146 Changes in syn-nodejs-puppeteer-6.2: • Updated versions of the bundled libraries in Chromium • Ephemeral storage monitoring— This runtime adds ephemeral storage monitoring in customer accounts. • Bug fixes syn-nodejs-puppeteer-5.2 Major dependencies: • Lambda runtime Node.js 16.x • Puppeteer-core version 19.7.0 • Chromium version 111.0.5563.146 Updates in syn-nodejs-puppeteer-5.2: • Updated versions of the bundled libraries in Chromium • Bug fixes Deprecated runtime versions for Node.js and Puppeteer The following runtimes for Node.js and Puppeteer have been deprecated. For information about runtime deprecation dates, see CloudWatch Synthetics runtime deprecation dates. syn-nodejs-puppeteer-6.1 Major dependencies: • Lambda runtime Node.js 18.x • Puppeteer-core version 19.7.0 • Chromium version 111.0.5563.146 Updates in syn-nodejs-puppeteer-6.1: Creating a canary 1666 Amazon CloudWatch User Guide • Stability improvements— Added auto-retry logic for handling intermittent Puppeteer launch errors. • Dependency upgrades— Upgrades for some third-party dependency packages. • Canaries without Amazon S3 permissions— Bug fixes, such that canaries that don't have any Amazon S3 permissions can still run. These canaries with no Amazon S3 permissions won't be able to upload screenshots or other artifacts to Amazon S3. For more information about permissions for canaries, see Required roles and permissions for canaries. Important IMPORTANT: The included AWS SDK for JavaScript v2 dependency will be removed and updated to use AWS SDK for JavaScript v3 in a future runtime release. When that happens, you can update your canary code references. Alternatively, you can continue referencing and using the included AWS SDK for JavaScript
acw-ug-446
acw-ug.pdf
446
S3 permissions— Bug fixes, such that canaries that don't have any Amazon S3 permissions can still run. These canaries with no Amazon S3 permissions won't be able to upload screenshots or other artifacts to Amazon S3. For more information about permissions for canaries, see Required roles and permissions for canaries. Important IMPORTANT: The included AWS SDK for JavaScript v2 dependency will be removed and updated to use AWS SDK for JavaScript v3 in a future runtime release. When that happens, you can update your canary code references. Alternatively, you can continue referencing and using the included AWS SDK for JavaScript v2 dependency by adding it as a dependency to your source code zip file. syn-nodejs-puppeteer-6.0 Major dependencies: • Lambda runtime Node.js 18.x • Puppeteer-core version 19.7.0 • Chromium version 111.0.5563.146 Updates in syn-nodejs-puppeteer-6.0: • Dependency upgrade— The Node.js dependency is upgraded to 18.x. • Intercept mode support— Puppeteer cooperative intercept mode support was added to the Synthetics canary runtime library. • Tracing behavior change— Changed default tracing behavior to trace only fetch and xhr requests, and not trace resource requests. You can enable the tracing of resource requests by configuring the traceResourceRequests option. • Duration metric refined— The Duration metric now excludes the operation time the canary uses to upload artifacts, take screenshots, and generate CloudWatch metrics. Duration metric values are reported to CloudWatch, and you can also see them in the Synthetics console. Creating a canary 1667 Amazon CloudWatch User Guide • Bug fix— Clean up core dump generated when Chromium crashes during a canary run. Important IMPORTANT: The included AWS SDK for JavaScript v2 dependency will be removed and updated to use AWS SDK for JavaScript v3 in a future runtime release. When that happens, you can update your canary code references. Alternatively, you can continue referencing and using the included AWS SDK for JavaScript v2 dependency by adding it as a dependency to your source code zip file. syn-nodejs-puppeteer-5.1 Major dependencies: • Lambda runtime Node.js 16.x • Puppeteer-core version 19.7.0 • Chromium version 111.0.5563.146 Bug fixes in syn-nodejs-puppeteer-5.1: • Bug fix— This runtime fixes a bug in syn-nodejs-puppeteer-5.0 where the HAR files created by the canaries were missing request headers. syn-nodejs-puppeteer-5.0 Major dependencies: • Lambda runtime Node.js 16.x • Puppeteer-core version 19.7.0 • Chromium version 111.0.5563.146 Updates in syn-nodejs-puppeteer-5.0: • Dependency upgrade— The Puppeteer-core version is updated to 19.7.0. The Chromium version is upgraded to 111.0.5563.146. Creating a canary 1668 Amazon CloudWatch Important User Guide The new Puppeteer-core version is not completely backward-compatible with previous versions of Puppeteer. Some of the changes in this version can cause existing canaries that use deprecated Puppeteer functions to fail. For more information, see the breaking changes in the change logs for Puppeteer-core versions 19.7.0 through 6.0, in Puppeteer change logs. syn-nodejs-puppeteer-4.0 Major dependencies: • Lambda runtime Node.js 16.x • Puppeteer-core version 5.5.0 • Chromium version 92.0.4512 Updates in syn-nodejs-puppeteer-4.0: • Dependency upgrade— The Node.js dependency is updated to 16.x. syn-nodejs-puppeteer-3.9 Important This runtime version was deprecated on January 8, 2024. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 14.x • Puppeteer-core version 5.5.0 • Chromium version 92.0.4512 Updates in syn-nodejs-puppeteer-3.9: Creating a canary 1669 Amazon CloudWatch User Guide • Dependency upgrades— Upgrades some third-party dependency packages. syn-nodejs-puppeteer-3.8 Important This runtime version was deprecated on January 8, 2024. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 14.x • Puppeteer-core version 5.5.0 • Chromium version 92.0.4512 Updates in syn-nodejs-puppeteer-3.8: • Profile cleanup— Chromium profiles are now cleaned up after each canary run. Bug fixes in syn-nodejs-puppeteer-3.8: • Bug fixes— Previously, visual monitoring canaries would sometimes stop working properly after a run with no screenshots. This is now fixed. syn-nodejs-puppeteer-3.7 Important This runtime version was deprecated on January 8, 2024. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 14.x • Puppeteer-core version 5.5.0 Creating a canary 1670 Amazon CloudWatch • Chromium version 92.0.4512 Updates in syn-nodejs-puppeteer-3.7: User Guide • Logging enhancement— The canary will upload logs to Amazon S3 even if it times out or crashes. • Lambda layer size reduced— The size of the Lambda layer used for canaries is reduced by 34%. Bug fixes in syn-nodejs-puppeteer-3.7: • Bug fixes— Japanese, Simplified Chinese, and Traditional Chinese fonts will render properly. syn-nodejs-puppeteer-3.6 Important This runtime version was deprecated on January 8, 2024. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 14.x • Puppeteer-core version 5.5.0 • Chromium version 92.0.4512 Updates in syn-nodejs-puppeteer-3.6: • More precise timestamps— The start time and stop time of canary runs are now precise to the millisecond. Creating a canary 1671 Amazon CloudWatch syn-nodejs-puppeteer-3.5 Important User Guide This runtime version was deprecated on January 8, 2024. For more information, see CloudWatch
acw-ug-447
acw-ug.pdf
447
by 34%. Bug fixes in syn-nodejs-puppeteer-3.7: • Bug fixes— Japanese, Simplified Chinese, and Traditional Chinese fonts will render properly. syn-nodejs-puppeteer-3.6 Important This runtime version was deprecated on January 8, 2024. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 14.x • Puppeteer-core version 5.5.0 • Chromium version 92.0.4512 Updates in syn-nodejs-puppeteer-3.6: • More precise timestamps— The start time and stop time of canary runs are now precise to the millisecond. Creating a canary 1671 Amazon CloudWatch syn-nodejs-puppeteer-3.5 Important User Guide This runtime version was deprecated on January 8, 2024. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 14.x • Puppeteer-core version 5.5.0 • Chromium version 92.0.4512 Updates in syn-nodejs-puppeteer-3.5: • Updated dependencies— The only new features in this runtime are the updated dependencies. syn-nodejs-puppeteer-3.4 Important This runtime version was deprecated on November 13, 2022. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 12.x • Puppeteer-core version 5.5.0 • Chromium version 88.0.4298.0 Updates in syn-nodejs-puppeteer-3.4: • Custom handler function— You can now use a custom handler function for your canary scripts. Previous runtimes required the script entry point to include .handler. Creating a canary 1672 Amazon CloudWatch User Guide You can also put canary scripts in any folder and pass the folder name as part of the handler. For example, MyFolder/MyScriptFile.functionname can be used as an entry point. • Expanded HAR file information— You can now see bad, pending, and incomplete requests in the HAR files produced by canaries. syn-nodejs-puppeteer-3.3 Important This runtime version was deprecated on November 13, 2022. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 12.x • Puppeteer-core version 5.5.0 • Chromium version 88.0.4298.0 Updates in syn-nodejs-puppeteer-3.3: • More options for artifact encryption— For canaries using this runtime or later, instead of using an AWS managed key to encrypt artifacts that the canary stores in Amazon S3, you can choose to use an AWS KMS customer managed key or an Amazon S3-managed key. For more information, see Encrypting canary artifacts. syn-nodejs-puppeteer-3.2 Important This runtime version was deprecated on November 13, 2022. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: Creating a canary 1673 Amazon CloudWatch • Lambda runtime Node.js 12.x • Puppeteer-core version 5.5.0 • Chromium version 88.0.4298.0 Updates in syn-nodejs-puppeteer-3.2: User Guide • visual monitoring with screenshots— Canaries using this runtime or later can compare a screenshot taken during a run with a baseline version of the same screenshot. If the screenshots are more different than a specified percentage threshold, the canary fails. For more information, see Visual monitoring or Visual monitoring blueprint. • New functions regarding sensitive data You can prevent sensitive data from appearing in canary logs and reports. For more information, see SyntheticsLogHelper class. • Deprecated function The RequestResponseLogHelper class is deprecated in favor of other new configuration options. For more information, see RequestResponseLogHelper class. syn-nodejs-puppeteer-3.1 Important This runtime version was deprecated on November 13, 2022. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 12.x • Puppeteer-core version 5.5.0 • Chromium version 88.0.4298.0 Updates in syn-nodejs-puppeteer-3.1: • Ability to configure CloudWatch metrics— With this runtime, you can disable the metrics that you do not require. Otherwise, canaries publish various CloudWatch metrics for each canary run. • Screenshot linking— You can link a screenshot to a canary step after the step has completed. To do this, you take the screenshot by using the takeScreenshot method, using the name of the Creating a canary 1674 Amazon CloudWatch User Guide step that you want to associate the screenshot with. For example, you might want to perform a step, add a wait time, and then take the screenshot. • Heartbeat monitor blueprint can monitor multiple URLs— You can use the heartbeat monitoring blueprint in the CloudWatch console to monitor multiple URLs and see the status, duration, associated screenshots, and failure reason for each URL in the step summary of the canary run report. syn-nodejs-puppeteer-3.0 Important This runtime version was deprecated on November 13, 2022. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 12.x • Puppeteer-core version 5.5.0 • Chromium version 88.0.4298.0 Updates in syn-nodejs-puppeteer-3.0: • Upgraded dependencies— This version uses Puppeteer version 5.5.0, Node.js 12.x, and Chromium 88.0.4298.0. • Cross-Region bucket access— You can now specify an S3 bucket in another Region as the bucket where your canary stores its log files, screenshots, and HAR files. • New functions available— This version adds library functions to retrieve the canary name and the Synthetics runtime version. For more information, see Synthetics class. syn-nodejs-2.2 This section contains information about the syn-nodejs-2.2 runtime version. Creating a canary 1675 Amazon CloudWatch Important User Guide This runtime version was
acw-ug-448
acw-ug.pdf
448
Puppeteer-core version 5.5.0 • Chromium version 88.0.4298.0 Updates in syn-nodejs-puppeteer-3.0: • Upgraded dependencies— This version uses Puppeteer version 5.5.0, Node.js 12.x, and Chromium 88.0.4298.0. • Cross-Region bucket access— You can now specify an S3 bucket in another Region as the bucket where your canary stores its log files, screenshots, and HAR files. • New functions available— This version adds library functions to retrieve the canary name and the Synthetics runtime version. For more information, see Synthetics class. syn-nodejs-2.2 This section contains information about the syn-nodejs-2.2 runtime version. Creating a canary 1675 Amazon CloudWatch Important User Guide This runtime version was deprecated on May 28, 2021. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 10.x • Puppeteer-core version 3.3.0 • Chromium version 83.0.4103.0 Changes in syn-nodejs-2.2: • Monitor your canaries as HTTP steps— You can now test multiple APIs in a single canary. Each API is tested as a separate HTTP step, and CloudWatch Synthetics monitors the status of each step using step metrics and the CloudWatch Synthetics step report. CloudWatch Synthetics creates SuccessPercent and Duration metrics for each HTTP step. This functionality is implemented by the executeHttpStep(stepName, requestOptions, callback, stepConfig) function. For more information, see executeHttpStep(stepName, requestOptions, [callback], [stepConfig]). The API canary blueprint is updated to use this new feature. • HTTP request reporting— You can now view detailed HTTP requests reports which capture details such as request/response headers, response body, status code, error and performance timings, TCP connection time, TLS handshake time, first byte time, and content transfer time. All HTTP requests which use the HTTP/HTTPS module under the hood are captured here. Headers and response body are not captured by default but can be enabled by setting configuration options. • Global and step-level configuration— You can set CloudWatch Synthetics configurations at the global level, which are applied to all steps of canaries. You can also override these configurations at the step level by passing configuration key/value pairs to enable or disable certain options. For more information, see SyntheticsConfiguration class. Creating a canary 1676 Amazon CloudWatch User Guide • Continue on step failure configuration— You can choose to continue canary execution when a step fails. For the executeHttpStep function, this is turned on by default. You can set this option once at global level or set it differently per-step. syn-nodejs-2.1 Important This runtime version was deprecated on May 28, 2021. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 10.x • Puppeteer-core version 3.3.0 • Chromium version 83.0.4103.0 Updates in syn-nodejs-2.1: • Configurable screenshot behavior— Provides the ability to turn off the capturing of screenshots by UI canaries. In canaries that use previous versions of the runtimes, UI canaries always capture screenshots before and after each step. With syn-nodejs-2.1, this is configurable. Turning off screenshots can reduce your Amazon S3 storage costs, and can help you comply with HIPAA regulations. For more information, see SyntheticsConfiguration class. • Customize the Google Chrome launch parameters You can now configure the arguments used when a canary launches a Google Chrome browser window. For more information, see launch(options). There can be a small increase in canary duration when using syn-nodejs-2.0 or later, compared to earlier versions of the canary runtimes. Creating a canary 1677 Amazon CloudWatch syn-nodejs-2.0 Important User Guide This runtime version was deprecated on May 28, 2021. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 10.x • Puppeteer-core version 3.3.0 • Chromium version 83.0.4103.0 Updates in syn-nodejs-2.0: • Upgraded dependencies— This runtime version uses Puppeteer-core version 3.3.0 and Chromium version 83.0.4103.0 • Support for X-Ray active tracing. When a canary has tracing enabled, X-Ray traces are sent for all calls made by the canary that use the browser, the AWS SDK, or HTTP or HTTPS modules. Canaries with tracing enabled appear on the X-Ray Trace Map, even when they don't send requests to other services or applications that have tracing enabled. For more information, see Canaries and X-Ray tracing. • Synthetics reporting— For each canary run, CloudWatch Synthetics creates a report named SyntheticsReport-PASSED.json or SyntheticsReport-FAILED.json which records data such as start time, end time, status, and failures. It also records the PASSED/FAILED status of each step of the canary script, and failures and screenshots captured for each step. • Broken link checker report— The new version of the broken link checker included in this runtime creates a report that includes the links that were checked, status code, failure reason (if any), and source and destination page screenshots. • New CloudWatch metrics— Synthetics publishes metrics named 2xx, 4xx, 5xx, and RequestFailed in the CloudWatchSynthetics namespace. These metrics show the number of 200s, 400s, 500s, and request failures in the canary runs. With this runtime version, these metrics are reported only for UI
acw-ug-449
acw-ug.pdf
449
PASSED/FAILED status of each step of the canary script, and failures and screenshots captured for each step. • Broken link checker report— The new version of the broken link checker included in this runtime creates a report that includes the links that were checked, status code, failure reason (if any), and source and destination page screenshots. • New CloudWatch metrics— Synthetics publishes metrics named 2xx, 4xx, 5xx, and RequestFailed in the CloudWatchSynthetics namespace. These metrics show the number of 200s, 400s, 500s, and request failures in the canary runs. With this runtime version, these metrics are reported only for UI canaries, and are not reported for API canaries. They are also reported for API canaries starting with runtime version syn-nodejs-puppeteeer-2.2. • Sortable HAR files— You can now sort your HAR files by status code, request size, and duration. Creating a canary 1678 Amazon CloudWatch User Guide • Metrics timestamp— CloudWatch metrics are now reported based on the Lambda invocation time instead of the canary run end time. Bug fixes in syn-nodejs-2.0: • Fixed the issue of canary artifact upload errors not being reported. Such errors are now surfaced as execution errors. • Fixed the issue of redirected requests (3xx) being incorrectly logged as errors. • Fixed the issue of screenshots being numbered starting from 0. They should now start with 1. • Fixed the issue of screenshots being garbled for Chinese and Japanese fonts. There can be a small increase in canary duration when using syn-nodejs-2.0 or later, compared to earlier versions of the canary runtimes. syn-nodejs-2.0-beta Important This runtime version was deprecated on February 8, 2021. For more information, see CloudWatch Synthetics runtime support policy. Major dependencies: • Lambda runtime Node.js 10.x • Puppeteer-core version 3.3.0 • Chromium version 83.0.4103.0 Changes in syn-nodejs-2.0-beta: • Upgraded dependencies— This runtime version uses Puppeteer-core version 3.3.0 and Chromium version 83.0.4103.0 • Synthetics reporting— For each canary run, CloudWatch Synthetics creates a report named SyntheticsReport-PASSED.json or SyntheticsReport-FAILED.json which records data such as start time, end time, status, and failures. It also records the PASSED/FAILED status of each step of the canary script, and failures and screenshots captured for each step. Creating a canary 1679 Amazon CloudWatch User Guide • Broken link checker report— The new version of the broken link checker included in this runtime creates a report that includes the links that were checked, status code, failure reason (if any), and source and destination page screenshots. • New CloudWatch metrics— Synthetics publishes metrics named 2xx, 4xx, 5xx, and RequestFailed in the CloudWatchSynthetics namespace. These metrics show the number of 200s, 400s, 500s, and request failures in the canary runs. These metrics are reported only for UI canaries, and are not reported for API canaries. • Sortable HAR files— You can now sort your HAR files by status code, request size, and duration. • Metrics timestamp— CloudWatch metrics are now reported based on the Lambda invocation time instead of the canary run end time. Bug fixes in syn-nodejs-2.0-beta: • Fixed the issue of canary artifact upload errors not being reported. Such errors are now surfaced as execution errors. • Fixed the issue of redirected requests (3xx) being incorrectly logged as errors. • Fixed the issue of screenshots being numbered starting from 0. They should now start with 1. • Fixed the issue of screenshots being garbled for Chinese and Japanese fonts. syn-1.0 The first Synthetics runtime version is syn-1.0. Major dependencies: • Lambda runtime Node.js 10.x • Puppeteer-core version 1.14.0 • The Chromium version that matches Puppeteer-core 1.14.0 Runtime versions using Python and Selenium Webdriver The following sections contain information about the CloudWatch Synthetics runtime versions for Python and Selenium Webdriver. Selenium is an open-source browser automation tool. For more information about Selenium, see www.selenium.dev/ Creating a canary 1680 Amazon CloudWatch User Guide The naming convention for these runtime versions is syn-language-framework-majorversion.minorversion. syn-python-selenium-5.1 Version 5.1 is the newest CloudWatch Synthetics runtime for Python and Selenium. Major dependencies: • Python 3.9 • Selenium 4.21.0 • Chromium version 131.0.6778.264 Changes in syn-python-selenium-5.1 • Minor updates on metric emission. • Supports dry runs for the canary which allows for adhoc executions or performing a safe canary update. Previous runtime versions for Python and Selenium The following earlier runtime versions for Python and Selenium are still supported. syn-python-selenium-5.0 Version 5.0 is the newest CloudWatch Synthetics runtime for Python and Selenium. Major dependencies: • Python 3.9 • Selenium 4.21.0 • Chromium version 131.0.6778.264 Changes in syn-python-selenium-5.0: • Automatic retry if the browser fails to launch. Creating a canary 1681 Amazon CloudWatch syn-python-selenium-4.1 User Guide Version 4.1 is the newest CloudWatch Synthetics runtime for Python and Selenium. Major dependencies: • Python 3.9 • Selenium 4.15.1 • Chromium version 126.0.6478.126 Changes in syn-python-selenium-4.1: • Addresses security vulnerability– This runtime has an update to address the CVE-2024-39689 vulnerability. syn-python-selenium-4.0 Major dependencies:
acw-ug-450
acw-ug.pdf
450
earlier runtime versions for Python and Selenium are still supported. syn-python-selenium-5.0 Version 5.0 is the newest CloudWatch Synthetics runtime for Python and Selenium. Major dependencies: • Python 3.9 • Selenium 4.21.0 • Chromium version 131.0.6778.264 Changes in syn-python-selenium-5.0: • Automatic retry if the browser fails to launch. Creating a canary 1681 Amazon CloudWatch syn-python-selenium-4.1 User Guide Version 4.1 is the newest CloudWatch Synthetics runtime for Python and Selenium. Major dependencies: • Python 3.9 • Selenium 4.15.1 • Chromium version 126.0.6478.126 Changes in syn-python-selenium-4.1: • Addresses security vulnerability– This runtime has an update to address the CVE-2024-39689 vulnerability. syn-python-selenium-4.0 Major dependencies: • Python 3.9 • Selenium 4.15.1 • Chromium version 126.0.6478.126 Changes in syn-python-selenium-4.0: • Bug fixes for errors in HAR parser logging. syn-python-selenium-3.0 Major dependencies: • Python 3.8 • Selenium 4.15.1 • Chromium version 121.0.6167.139 Changes in syn-python-selenium-3.0: Creating a canary 1682 Amazon CloudWatch User Guide • Updated versions of the bundled libraries in Chromium— The Chromium dependency is updated to a new version. syn-python-selenium-2.1 Major dependencies: • Python 3.8 • Selenium 4.15.1 • Chromium version 111.0.5563.146 Changes in syn-python-selenium-2.1: • Updated versions of the bundled libraries in Chromium— The Chromium and Selenium dependencies are updated to new versions. Deprecated runtime versions for Python and Selenium The following earlier runtime versions for Python and Selenium have been deprecated. For information about runtime deprecation dates, see CloudWatch Synthetics runtime deprecation dates. syn-python-selenium-2.0 Major dependencies: • Python 3.8 • Selenium 4.10.0 • Chromium version 111.0.5563.146 Changes in syn-python-selenium-2.0: • Updated dependencies— The Chromium and Selenium dependencies are updated to new versions. Bug fixes in syn-python-selenium-2.0: • Timestamp added— A timestamp has been added to canary logs. Creating a canary 1683 Amazon CloudWatch User Guide • Session re-use— A bug was fixed so that canaries are now prevented from reusing the session from their previous canary run. syn-python-selenium-1.3 Major dependencies: • Python 3.8 • Selenium 3.141.0 • Chromium version 92.0.4512.0 Changes in syn-python-selenium-1.3: • More precise timestamps— The start time and stop time of canary runs are now precise to the millisecond. syn-python-selenium-1.2 Major dependencies: • Python 3.8 • Selenium 3.141.0 • Chromium version 92.0.4512.0 • Updated dependencies— The only new features in this runtime are the updated dependencies. syn-python-selenium-1.1 Major dependencies: • Python 3.8 • Selenium 3.141.0 • Chromium version 83.0.4103.0 Features: Creating a canary 1684 Amazon CloudWatch User Guide • Custom handler function— You can now use a custom handler function for your canary scripts. Previous runtimes required the script entry point to include .handler. You can also put canary scripts in any folder and pass the folder name as part of the handler. For example, MyFolder/MyScriptFile.functionname can be used as an entry point. • Configuration options for adding metrics and step failure configurations— These options were already available in runtimes for Node.js canaries. For more information, see SyntheticsConfiguration class. • Custom arguments in Chrome — You can now open a browser in incognito mode or pass in proxy server configuration. For more information, see Chrome(). • Cross-Region artifact buckets— A canary can store its artifacts in an Amazon S3 bucket in a different Region. • Bug fixes, including a fix for the index.py issue— With previous runtimes, a canary file named index.py caused exceptions because it conflicted with the name of the library file. This issue is now fixed. syn-python-selenium-1.0 Major dependencies: • Python 3.8 • Selenium 3.141.0 • Chromium version 83.0.4103.0 Features: • Selenium support— You can write canary scripts using the Selenium test framework. You can bring your Selenium scripts from elsewhere into CloudWatch Synthetics with minimal changes, and they will work with AWS services. Writing a canary script The following sections explain how to write a canary script and how to integrate a canary with other AWS services and with external dependencies and libraries. Topics Creating a canary 1685 Amazon CloudWatch User Guide • Writing a Node.js canary script using the Playwright runtime • Writing a Node.js canary script using the Puppeteer runtime • Writing a Python canary script • Changing an existing Selenium script to use a Synthetics canary • Changing an existing Puppeteer Synthetics script to authenticate non-standard certificates Writing a Node.js canary script using the Playwright runtime Topics • Packaging your Node.js canary files for the Playwright runtime • Changing an existing Playwright script to use as a CloudWatch Synthetics canary • CloudWatch Synthetics configurations Packaging your Node.js canary files for the Playwright runtime Your canary script comprises of a .js (CommonJS syntax) or .mjs (ES syntax) file containing your Synthetics handler code, together with any additional packages and modules your code depends on. Scripts created in ES (ECMAScript) format should either use .mjs as the extension or include a package.json file with the "type": "module" field set. Unlike other runtimes like Node.js Puppeteer, you are not required to save your scripts in a
acw-ug-451
acw-ug.pdf
451
for the Playwright runtime • Changing an existing Playwright script to use as a CloudWatch Synthetics canary • CloudWatch Synthetics configurations Packaging your Node.js canary files for the Playwright runtime Your canary script comprises of a .js (CommonJS syntax) or .mjs (ES syntax) file containing your Synthetics handler code, together with any additional packages and modules your code depends on. Scripts created in ES (ECMAScript) format should either use .mjs as the extension or include a package.json file with the "type": "module" field set. Unlike other runtimes like Node.js Puppeteer, you are not required to save your scripts in a specific folder structure. You can package your scripts directly. Use your preferred zip utility to create a .zip file with your handler file at the root. If your canary script depends on additional packages or modules that aren't included in the Synthetics runtime, you can add these dependencies to your .zip file. To do so, you can install your function's required libraries in the node_modules directory by running the npm install command. The following example CLI commands create a .zip file named my_deployment_package.zip containing the index.js or index.mjs file (Synthetics handler) and its dependencies. In the example, you install dependencies using the npm package manager. ~/my_function ### index.mjs ### synthetics.json ### myhelper-util.mjs ### node_modules ### mydependency Creating a canary 1686 Amazon CloudWatch User Guide Create a .zip file that contains the contents of your project folder at the root. Use the r (recursive) option, as shown in the following example, to ensure that zip compresses the subfolders. zip -r my_deployment_package.zip . Add a Synthetics configuration file to configure the behavior of CloudWatch Synthetics. You can create a synthetics.json file and save it at the same path as your entry point or handler file. Optionally, you can also store your entry point file in a folder structure of your choice. However, be sure that the folder path is specified in your handler name. Handler name Be sure to set your canary’s script entry point (handler) as myCanaryFilename.functionName to match the file name of your script’s entry point. You can optionally store the canary in a separate folder such as myFolder/my_canary_filename.mjs. If you store it in a separate folder, specify that path in your script entry point, such as myFolder/my_canary_filename.functionName. Changing an existing Playwright script to use as a CloudWatch Synthetics canary You can edit an existing script for Node.js and Playwright to be used as a canary. For more information about Playwright, see the Playwright library documentation. You can use the following Playwright script that is saved in file exampleCanary.mjs. import { chromium } from 'playwright'; import { expect } from '@playwright/test'; const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('https://example.com', {timeout: 30000}); await page.screenshot({path: 'example-home.png'}); const title = await page.title(); expect(title).toEqual("Example Domain"); await browser.close(); Convert the script by performing the following steps: 1. Create and export a handler function. The handler is the entry point function for the script. You can choose any name for the handler function, but the function that is Creating a canary 1687 Amazon CloudWatch User Guide used in your script should be the same as in your canary handler. If your script name is exampleCanary.mjs, and the handler function name is myhandler, your canary handler is named exampleCanary.myhandler. In the following example, the handler function name is handler. exports.handler = async () => { // Your script here }; 2. Import the Synthetics Playwright module as a dependency. import { synthetics } from '@amzn/synthetics-playwright'; 3. Launch a browser using the Synthetics Launch function. const browser = await synthetics.launch(); 4. Create a new Playwright page by using the Synthetics newPage function. const page = await synthetics.newPage(); Your script is now ready to be run as a Synthetics canary. The following is the the updated script: Updated script in ES6 format The script file saved with a .mjs extension. import { synthetics } from '@amzn/synthetics-playwright'; import { expect } from '@playwright/test'; export const handler = async (event, context) => { try { // Launch a browser const browser = await synthetics.launch(); // Create a new page const page = await synthetics.newPage(browser); // Navigate to a website await page.goto('https://www.example.com', {timeout: 30000}); Creating a canary 1688 Amazon CloudWatch // Take screenshot await page.screenshot({ path: '/tmp/example.png' }); User Guide // Verify the page title const title = await page.title(); expect(title).toEqual("Example Domain"); } finally { // Ensure browser is closed await synthetics.close(); } }; Updated script in CommonJS format The script file saved with a .js extension. const { synthetics } = require('@amzn/synthetics-playwright'); const { expect } = require('@playwright/test'); exports.handler = async (event) => { try { const browser = await synthetics.launch(); const page = await synthetics.newPage(browser); await page.goto('https://www.example.com', {timeout: 30000}); await page.screenshot({ path: '/tmp/example.png' }); const title = await page.title(); expect(title).toEqual("Example Domain"); } finally { await synthetics.close();
acw-ug-452
acw-ug.pdf
452
Amazon CloudWatch // Take screenshot await page.screenshot({ path: '/tmp/example.png' }); User Guide // Verify the page title const title = await page.title(); expect(title).toEqual("Example Domain"); } finally { // Ensure browser is closed await synthetics.close(); } }; Updated script in CommonJS format The script file saved with a .js extension. const { synthetics } = require('@amzn/synthetics-playwright'); const { expect } = require('@playwright/test'); exports.handler = async (event) => { try { const browser = await synthetics.launch(); const page = await synthetics.newPage(browser); await page.goto('https://www.example.com', {timeout: 30000}); await page.screenshot({ path: '/tmp/example.png' }); const title = await page.title(); expect(title).toEqual("Example Domain"); } finally { await synthetics.close(); } }; CloudWatch Synthetics configurations You can configure the behavior of the Synthetics Playwright runtime by providing an optional JSON configuration file named synthetics.json. This file should be packaged in the same location as the handler file. Though a configuration file is optional, f you don't provide a configuration file, or a configuration key is missing, CloudWatch assumes defaults. Packaging your configuration file The following are supported configuration values, and their defaults. Creating a canary 1689 User Guide Amazon CloudWatch { "step": { "screenshotOnStepStart": false, "screenshotOnStepSuccess": false, "screenshotOnStepFailure": false, "stepSuccessMetric": true, "stepDurationMetric": true, "continueOnStepFailure": true, "stepsReport": true }, "report": { "includeRequestHeaders": true, "includeResponseHeaders": true, "includeUrlPassword": false, "includeRequestBody": true, "includeResponseBody": true, "restrictedHeaders": ['x-amz-security-token', 'Authorization'], // Value of these headers is redacted from logs and reports "restrictedUrlParameters": ['Session', 'SigninToken'] // Values of these url parameters are redacted from logs and reports }, "logging": { "logRequest": false, "logResponse": false, "logResponseBody": false, "logRequestBody": false, "logRequestHeaders": false, "logResponseHeaders": false }, "httpMetrics": { "metric_2xx": true, "metric_4xx": true, "metric_5xx": true, "failedRequestsMetric": true, "aggregatedFailedRequestsMetric": true, "aggregated2xxMetric": true, "aggregated4xxMetric": true, "aggregated5xxMetric": true }, "canaryMetrics": { "failedCanaryMetric": true, "aggregatedFailedCanaryMetric": true }, Creating a canary 1690 Amazon CloudWatch "userAgent": "", "har": true } Step configurations User Guide • screenshotOnStepStart – Determines if Synthetics should capture a screenshot before the step starts. The default is true. • screenshotOnStepSuccess – Determines if Synthetics should capture a screenshot after a step has succeeded. The default is true. • screenshotOnStepFailure – Determines if Synthetics should capture a screenshot after a step has failed. The default is true. • continueOnStepFailure – Determines if a script should continue even after a step has failed. The default is false. • stepSuccessMetric – Determines if a step’s SuccessPercent metric is emitted. The SuccessPercent metric for a step is 100 for the canary run if the step succeeds, and 0 if the step fails. The default is true. • stepDurationMetric – Determines if a step's Duration metric is emitted. The Duration metric is emitted as a duration, in milliseconds, of the step's run. The default is true. Report configurations Includes all reports generated by CloudWatch Synthetics, such as a HAR file and a Synthetics steps report. Sensitive data redaction fields restrictedHeaders and restrictedUrlParameters also apply to logs generated by Synthetics. • includeRequestHeaders – Whether to include request headers in the report. The default is false. • includeResponseHeaders – Whether to include response headers in the report. The default is false. • includeUrlPassword – Whether to include a password that appears in the URL. By default, passwords that appear in URLs are redacted from logs and reports, to prevent the disclosure of sensitive data. The default is false. • includeRequestBody – Whether to include the request body in the report. The default is false. Creating a canary 1691 Amazon CloudWatch User Guide • includeResponseBody – Whether to include the response body in the report. The default is false. • restrictedHeaders – A list of header values to ignore, if headers are included. This applies to both request and response headers. For example, you can hide your credentials by passing includeRequestHeaders as true and restrictedHeaders as ['Authorization']. • restrictedUrlParameters – A list of URL path or query parameters to redact. This applies to URLs that appear in logs, reports, and errors. The parameter is case-insensitive. You can pass an asterisk (*) as a value to redact all URL path and query parameter values. The default is an empty array. • har – Determines if an HTTP archive (HAR) should be generated. The default is true. The following is an example of a report configurations file. "includeRequestHeaders": true, "includeResponseHeaders": true, "includeUrlPassword": false, "includeRequestBody": true, "includeResponseBody": true, "restrictedHeaders": ['x-amz-security-token', 'Authorization'], // Value of these headers is redacted from logs and reports "restrictedUrlParameters": ['Session', 'SigninToken'] // Values of these URL parameters are redacted from logs and reports Logging configurations Applies to logs generated by CloudWatch Synthetics. Controls the verbosity of request and response logs. • logRequest – Whether to log every request in canary logs. For UI canaries, this logs each request sent by the browser. The default is false. • logResponse – Whether to log every response in canary logs. For UI canaries, this logs every response received by the browser. The default is
acw-ug-453
acw-ug.pdf
453
true, "includeResponseBody": true, "restrictedHeaders": ['x-amz-security-token', 'Authorization'], // Value of these headers is redacted from logs and reports "restrictedUrlParameters": ['Session', 'SigninToken'] // Values of these URL parameters are redacted from logs and reports Logging configurations Applies to logs generated by CloudWatch Synthetics. Controls the verbosity of request and response logs. • logRequest – Whether to log every request in canary logs. For UI canaries, this logs each request sent by the browser. The default is false. • logResponse – Whether to log every response in canary logs. For UI canaries, this logs every response received by the browser. The default is false. • logRequestBody – Whether to log request bodies along with the requests in canary logs. This configuration applies only if logRequest is true. The default is false. • logResponseBody – Whether to log response bodies along with the requests in canary logs. This configuration applies only if logResponse is true. The default is false. Creating a canary 1692 Amazon CloudWatch User Guide • logRequestHeaders – Whether to log request headers along with the requests in canary logs. This configuration applies only if logRequest is true. The default is false. • logResponseHeaders – Whether to log response headers along with the responses in canary logs. This configuration applies only if logResponse is true. The default is false. HTTP metric configurations Configurations for metrics related to the count of network requests with different HTTP status codes, emitted by CloudWatch Synthetics for this canary. • metric_2xx – Whether to emit the 2xx metric (with the CanaryName dimension) for this canary. The default is true. • metric_4xx – Whether to emit the 4xx metric (with the CanaryName dimension) for this canary. The default is true. • metric_5xx – Whether to emit the 5xx metric (with the CanaryName dimension) for this canary. The default is true. • failedRequestsMetric – Whether to emit the failedRequests metric (with the CanaryName dimension) for this canary. The default is true. • aggregatedFailedRequestsMetric – Whether to emit the failedRequests metric (without the CanaryName dimension) for this canary. The default is true. • aggregated2xxMetric – Whether to emit the 2xx metric (without the CanaryName dimension) for this canary. The default is true. • aggregated4xxMetric – Whether to emit the 4xx metric (without the CanaryName dimension) for this canary. The default is true. • aggregated5xxMetric – Whether to emit the 5xx metric (without the CanaryName dimension) for this canary. The default is true. Canary metric configurations Configurations for other metrics emitted by CloudWatch Synthetics. • failedCanaryMetric – Whether to emit the Failed metric (with the CanaryName dimension) for this canary. The default is true. • aggregatedFailedCanaryMetric – Whether to emit the Failed metric (without the CanaryName dimension) for this canary. The default is true. Creating a canary 1693 Amazon CloudWatch Other configurations User Guide • userAgent – A string to append to the user agent. The user agent is a string that is included in request header, and identifies your browser to websites you visit when you use the headless browser. CloudWatch Synthetics automatically adds CloudWatchSynthetics/canary-arn to the user agent. The specified configuration is appended to the generated user agent. The default user agent value to append is an empty string (""). CloudWatch Synthetics environment variables Configure the logging level and format by using environment variables. Log format The CloudWatch Synthetics Playwright runtime creates CloudWatch logs for every canary run. Logs are written in JSON format for convenient querying. Optionally, you can change the log format to TEXT. • Environment variable name – CW_SYNTHETICS_LOG_FORMAT • Supported values – JSON, TEXT • Default – JSON Log levels Though enabling Debug mode increases verbosity, it can be useful for troubleshooting. • Environment variable name – CW_SYNTHETICS_LOG_LEVEL • Supported values – TRACE, DEBUG, INFO, WARN, ERROR, FATAL • Default – INFO Writing a Node.js canary script using the Puppeteer runtime Topics • Creating a CloudWatch Synthetics canary from scratch • Packaging your Node.js canary files • Changing an existing Puppeteer script to use as a Synthetics canary • Environment variables Creating a canary 1694 Amazon CloudWatch User Guide • Integrating your canary with other AWS services • Forcing your canary to use a static IP address Creating a CloudWatch Synthetics canary from scratch Here is an example minimal Synthetics Canary script. This script passes as a successful run, and returns a string. To see what a failing canary looks like, change let fail = false; to let fail = true;. You must define an entry point function for the canary script. To see how files are uploaded to the Amazon S3 location specified as the canary's ArtifactS3Location, create these files in the / tmp folder. All canary artifacts should be stored in /tmp, because it's the only writable directory. Be sure that the screenshot path is set to /tmp for any screenshots or other
acw-ug-454
acw-ug.pdf
454
is an example minimal Synthetics Canary script. This script passes as a successful run, and returns a string. To see what a failing canary looks like, change let fail = false; to let fail = true;. You must define an entry point function for the canary script. To see how files are uploaded to the Amazon S3 location specified as the canary's ArtifactS3Location, create these files in the / tmp folder. All canary artifacts should be stored in /tmp, because it's the only writable directory. Be sure that the screenshot path is set to /tmp for any screenshots or other files created by the script. Synthetics automatically uploads files in /tmp to an S3 bucket. /tmp/<name> After the script runs, the pass/fail status and the duration metrics are published to CloudWatch and the files under/tmp are uploaded to an S3 bucket. const basicCustomEntryPoint = async function () { // Insert your code here // Perform multi-step pass/fail check // Log decisions made and results to /tmp // Be sure to wait for all your code paths to complete // before returning control back to Synthetics. // In that way, your canary will not finish and report success // before your code has finished executing // Throw to fail, return to succeed let fail = false; if (fail) { throw "Failed basicCanary check."; } return "Successfully completed basicCanary checks."; }; Creating a canary 1695 Amazon CloudWatch User Guide exports.handler = async () => { return await basicCustomEntryPoint(); }; Next, we'll expand the script to use Synthetics logging and make a call using the AWS SDK. For demonstration purposes, this script will create an Amazon DynamoDB client and make a call to the DynamoDB listTables API. It logs the response to the request and logs either pass or fail depending on whether the request was successful. const log = require('SyntheticsLogger'); const AWS = require('aws-sdk'); // Require any dependencies that your script needs // Bundle additional files and dependencies into a .zip file with folder structure // nodejs/node_modules/additional files and folders const basicCustomEntryPoint = async function () { log.info("Starting DynamoDB:listTables canary."); let dynamodb = new AWS.DynamoDB(); var params = {}; let request = await dynamodb.listTables(params); try { let response = await request.promise(); log.info("listTables response: " + JSON.stringify(response)); } catch (err) { log.error("listTables error: " + JSON.stringify(err), err.stack); throw err; } return "Successfully completed DynamoDB:listTables canary."; }; exports.handler = async () => { return await basicCustomEntryPoint(); }; Packaging your Node.js canary files If you are uploading your canary scripts using an Amazon S3 location, your zip file should include your script under this folder structure: nodejs/node_modules/myCanaryFilename.js file. Creating a canary 1696 Amazon CloudWatch User Guide If you have more than a single .js file or you have a dependency that your script depends on, you can bundle them all into a single ZIP file that contains the folder structure nodejs/node_modules/myCanaryFilename.js file and other folders and files. If you are using syn-nodejs-puppeteer-3.4 or later, you can optionally put your canary files in another folder and creating your folder structure like this: nodejs/ node_modules/myFolder/myCanaryFilename.js file and other folders and files. Handler name Be sure to set your canary’s script entry point (handler) as myCanaryFilename.functionName to match the file name of your script’s entry point. If you are using a runtime earlier than syn- nodejs-puppeteer-3.4, then functionName must be handler. If you are using syn- nodejs-puppeteer-3.4 or later, you can choose any function name as the handler. If you are using syn-nodejs-puppeteer-3.4 or later, you can also optionally store the canary in a separate folder such as nodejs/node_modules/myFolder/my_canary_filename. If you store it in a separate folder, specify that path in your script entry point, such as myFolder/ my_canary_filename.functionName. Changing an existing Puppeteer script to use as a Synthetics canary This section explains how to take Puppeteer scripts and modify them to run as Synthetics canary scripts. For more information about Puppeteer, see Puppeteer API v1.14.0. We'll start with this example Puppeteer script: const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); await page.screenshot({path: 'example.png'}); await browser.close(); })(); The conversion steps are as follows: • Create and export a handler function. The handler is the entry point function for the script. If you are using a runtime earlier than syn-nodejs-puppeteer-3.4, the handler function must Creating a canary 1697 Amazon CloudWatch User Guide be named handler. If you are using syn-nodejs-puppeteer-3.4 or later, the function can have any name, but it must be the same name that is used in the script. Also, if you are using syn-nodejs-puppeteer-3.4 or later, you can store your scripts under any folder and specify that folder as part of the handler name. const basicPuppeteerExample = async function () {}; exports.handler = async () => { return await basicPuppeteerExample(); }; • Use the
acw-ug-455
acw-ug.pdf
455
function for the script. If you are using a runtime earlier than syn-nodejs-puppeteer-3.4, the handler function must Creating a canary 1697 Amazon CloudWatch User Guide be named handler. If you are using syn-nodejs-puppeteer-3.4 or later, the function can have any name, but it must be the same name that is used in the script. Also, if you are using syn-nodejs-puppeteer-3.4 or later, you can store your scripts under any folder and specify that folder as part of the handler name. const basicPuppeteerExample = async function () {}; exports.handler = async () => { return await basicPuppeteerExample(); }; • Use the Synthetics dependency. var synthetics = require('Synthetics'); • Use the Synthetics.getPage function to get a Puppeteer Page object. const page = await synthetics.getPage(); The page object returned by the Synthetics.getPage function has the page.on request, response and requestfailed events instrumented for logging. Synthetics also sets up HAR file generation for requests and responses on the page, and adds the canary ARN to the user- agent headers of outgoing requests on the page. The script is now ready to be run as a Synthetics canary. Here is the updated script: var synthetics = require('Synthetics'); // Synthetics dependency const basicPuppeteerExample = async function () { const page = await synthetics.getPage(); // Get instrumented page from Synthetics await page.goto('https://example.com'); await page.screenshot({path: '/tmp/example.png'}); // Write screenshot to /tmp folder }; exports.handler = async () => { // Exported handler function return await basicPuppeteerExample(); }; Creating a canary 1698 Amazon CloudWatch Environment variables User Guide You can use environment variables when creating canaries. This allows you to write a single canary script and then use that script with different values to quickly create multiple canaries that have a similar task. For example, suppose your organization has endpoints such as prod, dev, and pre-release for the different stages of your software development, and you need to create canaries to test each of these endpoints. You can write a single canary script that tests your software and then specify different values for the endpoint environment variable when you create each of the three canaries. Then, when you create a canary, you specify the script and the values to use for the environment variables. The names of environment variables can contain letters, numbers, and the underscore character. They must start with a letter and be at least two characters. The total size of your environment variables can't exceed 4 KB. You can't specify any Lambda reserved environment variables as the names of your environment variables. For more information about reserved environment variables, see Runtime environment variables. Important Environment variable keys and values are encrypted at rest using AWS owned AWS KMS keys. However, the environment variables are not encrypted on the client side. Do not store sensitive information in them. The following example script uses two environment variables. This script is for a canary that checks whether a webpage is available. It uses environment variables to parameterize both the URL that it checks and the CloudWatch Synthetics log level that it uses. The following function sets LogLevel to the value of the LOG_LEVEL environment variable. synthetics.setLogLevel(process.env.LOG_LEVEL); This function sets URL to the value of the URL environment variable. const URL = process.env.URL; Creating a canary 1699 Amazon CloudWatch User Guide This is the complete script. When you create a canary using this script, you specify values for the LOG_LEVEL and URL environment variables. var synthetics = require('Synthetics'); const log = require('SyntheticsLogger'); const pageLoadEnvironmentVariable = async function () { // Setting the log level (0-3) synthetics.setLogLevel(process.env.LOG_LEVEL); // INSERT URL here const URL = process.env.URL; let page = await synthetics.getPage(); //You can customize the wait condition here. For instance, //using 'networkidle2' may be less restrictive. const response = await page.goto(URL, {waitUntil: 'domcontentloaded', timeout: 30000}); if (!response) { throw "Failed to load page!"; } //Wait for page to render. //Increase or decrease wait time based on endpoint being monitored. await page.waitFor(15000); await synthetics.takeScreenshot('loaded', 'loaded'); let pageTitle = await page.title(); log.info('Page title: ' + pageTitle); log.debug('Environment variable:' + process.env.URL); //If the response status code is not a 2xx success code if (response.status() < 200 || response.status() > 299) { throw "Failed to load page!"; } }; exports.handler = async () => { return await pageLoadEnvironmentVariable(); }; Creating a canary 1700 Amazon CloudWatch User Guide Passing environment variables to your script To pass environment variables to your script when you create a canary in the console, specify the keys and values of the environment variables in the Environment variables section on the console. For more information, see Creating a canary. To pass environment variables through the API or AWS CLI, use the EnvironmentVariables parameter in the RunConfig section. The following is an example AWS CLI command that creates a canary that uses two environment variables with keys of Environment and Region. aws synthetics create-canary
acw-ug-456
acw-ug.pdf
456
await pageLoadEnvironmentVariable(); }; Creating a canary 1700 Amazon CloudWatch User Guide Passing environment variables to your script To pass environment variables to your script when you create a canary in the console, specify the keys and values of the environment variables in the Environment variables section on the console. For more information, see Creating a canary. To pass environment variables through the API or AWS CLI, use the EnvironmentVariables parameter in the RunConfig section. The following is an example AWS CLI command that creates a canary that uses two environment variables with keys of Environment and Region. aws synthetics create-canary --cli-input-json '{ "Name":"nameofCanary", "ExecutionRoleArn":"roleArn", "ArtifactS3Location":"s3://amzn-s3-demo-bucket-123456789012-us-west-2", "Schedule":{ "Expression":"rate(0 minute)", "DurationInSeconds":604800 }, "Code":{ "S3Bucket": "canarycreation", "S3Key": "cwsyn-mycanaryheartbeat-12345678-d1bd-1234- abcd-123456789012-12345678-6a1f-47c3-b291-123456789012.zip", "Handler":"pageLoadBlueprint.handler" }, "RunConfig": { "TimeoutInSeconds":60, "EnvironmentVariables": { "Environment":"Production", "Region": "us-west-1" } }, "SuccessRetentionPeriodInDays":13, "FailureRetentionPeriodInDays":13, "RuntimeVersion":"syn-nodejs-2.0" }' Integrating your canary with other AWS services All canaries can use the AWS SDK library. You can use this library when you write your canary to integrate the canary with other AWS services. To do so, you need to add the following code to your canary. For these examples, AWS Secrets Manager is used as the service that the canary is integrating with. Creating a canary 1701 User Guide Amazon CloudWatch • Import the AWS SDK. const AWS = require('aws-sdk'); • Create a client for the AWS service that you are integrating with. const secretsManager = new AWS.SecretsManager(); • Use the client to make API calls to that service. var params = { SecretId: secretName }; return await secretsManager.getSecretValue(params).promise(); The following canary script code snippet demonstrates an example of integration with Secrets Manager in more detail. var synthetics = require('Synthetics'); const log = require('SyntheticsLogger'); const AWS = require('aws-sdk'); const secretsManager = new AWS.SecretsManager(); const getSecrets = async (secretName) => { var params = { SecretId: secretName }; return await secretsManager.getSecretValue(params).promise(); } const secretsExample = async function () { let URL = "<URL>"; let page = await synthetics.getPage(); log.info(`Navigating to URL: ${URL}`); const response = await page.goto(URL, {waitUntil: 'domcontentloaded', timeout: 30000}); // Fetch secrets let secrets = await getSecrets("secretname") Creating a canary 1702 Amazon CloudWatch User Guide /** * Use secrets to login. * * Assuming secrets are stored in a JSON format like: * { * "username": "<USERNAME>", * "password": "<PASSWORD>" * } **/ let secretsObj = JSON.parse(secrets.SecretString); await synthetics.executeStep('login', async function () { await page.type(">USERNAME-INPUT-SELECTOR<", secretsObj.username); await page.type(">PASSWORD-INPUT-SELECTOR<", secretsObj.password); await Promise.all([ page.waitForNavigation({ timeout: 30000 }), await page.click(">SUBMIT-BUTTON-SELECTOR<") ]); }); // Verify login was successful await synthetics.executeStep('verify', async function () { await page.waitForXPath(">SELECTOR<", { timeout: 30000 }); }); }; exports.handler = async () => { return await secretsExample(); }; Forcing your canary to use a static IP address You can set up a canary so that it uses a static IP address. To force a canary to use a static IP address 1. Create a new VPC. For more information, see Using DNS with Your VPC. 2. Create a new internet gateway. For more information, see Adding an internet gateway to your VPC. 3. Create a public subnet inside your new VPC. 4. Add a new route table to the VPC. Creating a canary 1703 Amazon CloudWatch User Guide 5. Add a route in the new route table, that goes from 0.0.0.0/0 to the internet gateway. 6. Associate the new route table with the public subnet. 7. Create an elastic IP address. For more information, see Elastic IP addresses . 8. Create a new NAT gateway and assign it to the public subnet and the elastic IP address. 9. Create a private subnet inside the VPC. 10. Add a route to the VPC default route table, that goes from 0.0.0.0/0 to the NAT gateway 11. Create your canary. Writing a Python canary script This script passes as a successful run, and returns a string. To see what a failing canary looks like, change fail = False to fail = True def basic_custom_script(): # Insert your code here # Perform multi-step pass/fail check # Log decisions made and results to /tmp # Be sure to wait for all your code paths to complete # before returning control back to Synthetics. # In that way, your canary will not finish and report success # before your code has finished executing fail = False if fail: raise Exception("Failed basicCanary check.") return "Successfully completed basicCanary checks." def handler(event, context): return basic_custom_script() Packaging your Python canary files If you have more than one .py file or your script has a dependency, you can bundle them all into a single ZIP file. If you use the syn-python-selenium-1.1 runtime, the ZIP file must contain your main canary .py file within a python folder, such as python/my_canary_filename.py. If you use syn-python-selenium-1.1 or later, you can optionally use a different folder , such as python/myFolder/my_canary_filename.py. This ZIP file should contain all necessary folders and files, but the
acw-ug-457
acw-ug.pdf
457
fail = False if fail: raise Exception("Failed basicCanary check.") return "Successfully completed basicCanary checks." def handler(event, context): return basic_custom_script() Packaging your Python canary files If you have more than one .py file or your script has a dependency, you can bundle them all into a single ZIP file. If you use the syn-python-selenium-1.1 runtime, the ZIP file must contain your main canary .py file within a python folder, such as python/my_canary_filename.py. If you use syn-python-selenium-1.1 or later, you can optionally use a different folder , such as python/myFolder/my_canary_filename.py. This ZIP file should contain all necessary folders and files, but the other files do not need to be in the python folder. Creating a canary 1704 Amazon CloudWatch User Guide Be sure to set your canary’s script entry point as my_canary_filename.functionName to match the file name and function name of your script’s entry point. If you are using the syn-python- selenium-1.0 runtime, then functionName must be handler. If you are using syn-python- selenium-1.1 or later, this handler name restriction doesn't apply, and you can also optionally store the canary in a separate folder such as python/myFolder/my_canary_filename.py. If you store it in a separate folder, specify that path in your script entry point, such as myFolder/ my_canary_filename.functionName. Changing an existing Selenium script to use a Synthetics canary You can quickly modify an existing script for Python and Selenium to be used as a canary. For more information about Selenium, see www.selenium.dev/. For this example, we'll start with the following Selenium script: from selenium import webdriver def basic_selenium_script(): browser = webdriver.Chrome() browser.get('https://example.com') browser.save_screenshot('loaded.png') basic_selenium_script() The conversion steps are as follows. To convert a Selenium script to be used as a canary 1. Change the import statement to use Selenium from the aws_synthetics module: from aws_synthetics.selenium import synthetics_webdriver as webdriver The Selenium module from aws_synthetics ensures that the canary can emit metrics and logs, generate a HAR file, and work with other CloudWatch Synthetics features. 2. Create a handler function and call your Selenium method. The handler is the entry point function for the script. If you are using syn-python-selenium-1.0, the handler function must be named handler. If you are using syn-python-selenium-1.1 or later, the function can have any name, but it must be the same name that is used in the script. Also, if you are using syn-python- Creating a canary 1705 Amazon CloudWatch User Guide selenium-1.1 or later, you can store your scripts under any folder and specify that folder as part of the handler name. def handler(event, context): basic_selenium_script() The script is now updated to be a CloudWatch Synthetics canary. Here is the updated script: from aws_synthetics.selenium import synthetics_webdriver as webdriver def basic_selenium_script(): browser = webdriver.Chrome() browser.get('https://example.com') browser.save_screenshot('loaded.png') def handler(event, context): basic_selenium_script() Changing an existing Puppeteer Synthetics script to authenticate non-standard certificates One important use case for Synthetics canaries is for you to monitor your own endpoints. If you want to monitor an endpoint that isn't ready for external traffic, this monitoring can sometimes mean that you don't have a proper certificate signed by a trusted third-party certificate authority. Two possible solutions to this scenario are as follows: • To authenticate a client certificate, see How to validate authentication using Amazon CloudWatch Synthetics – Part 2. • To authenticate a self-signed certificate, see How to validate authentication with self-signed certificates in Amazon CloudWatch Synthetics You are not limited to these two options when you use CloudWatch Synthetics canaries. You can extend these features and add your business logic by extending the canary code. Creating a canary 1706 Amazon CloudWatch Note User Guide Synthetics canaries running on Python runtimes innately have the --ignore- certificate-errors flag enabled, so those canaries shouldn't have any issues reaching sites with non-standard certificate configurations. Library functions available for canary scripts CloudWatch Synthetics includes several built-in classes and functions that you can call when writing Node.js scripts to use as canaries. Some apply to both UI and API canaries. Others apply to UI canaries only. A UI canary is a canary that uses the getPage() function and uses Puppeteer as a web driver to navigate and interact with webpages. Note Whenever you upgrade a canary to use a new version of the the Synthetics runtime, all Synthetics library functions that your canary uses are also automatically upgraded to the same version of NodeJS that the Synthetics runtime supports. Topics • Library functions available for Node.js canary scripts using Playwright • Library functions available for Node.js canary scripts using Puppeteer • Library functions available for Python canary scripts using Selenium Library functions available for Node.js canary scripts using Playwright This section describes the library functions that are available for canary scripts using the Node.js Playwright runtime. Topics • launch • newPage • close Creating a canary 1707 Amazon CloudWatch • getDefaultLaunchOptions • executeStep launch User Guide This function launches
acw-ug-458
acw-ug.pdf
458
functions that your canary uses are also automatically upgraded to the same version of NodeJS that the Synthetics runtime supports. Topics • Library functions available for Node.js canary scripts using Playwright • Library functions available for Node.js canary scripts using Puppeteer • Library functions available for Python canary scripts using Selenium Library functions available for Node.js canary scripts using Playwright This section describes the library functions that are available for canary scripts using the Node.js Playwright runtime. Topics • launch • newPage • close Creating a canary 1707 Amazon CloudWatch • getDefaultLaunchOptions • executeStep launch User Guide This function launches a Chromium browser using a Playwright launch function, and returns the browser object. It decompresses browser binaries and launches the chromium browser by using default options suitable for a headless browser. For more information about the launch function, see launch in the Playwright documentation. Usage const browser = await synthetics.launch(); Arguments options options (optional) is a configurable set of options for the browser. Returns Promise <Browser> where Browser is a Playwright browser instance. If this function is called again, a previously-opened browser is closed before initiating a new browser. You can override launch parameters used by CloudWatch Synthetics, and pass additional parameters when launching the browser. For example, the following code snippet launches a browser with default arguments and a default executable path, but with a viewport of 800 x 600 pixels. For more information, see Playwright launch options in the Playwright documentation. const browser = await synthetics.launch({ defaultViewport: { "deviceScaleFactor": 1, "width": 800, "height": 600 }}); You can also add or override Chromium flags passed on by default to the browser. For example, you can disable web security by adding a --disable-web-security flag to arguments in the CloudWatch Synthetics launch parameters: // This function adds the --disable-web-security flag to the launch parameters Creating a canary 1708 Amazon CloudWatch User Guide const defaultOptions = await synthetics.getDefaultLaunchOptions(); const launchArgs = [...defaultOptions.args, '--disable-web-security']; const browser = await synthetics.launch({ args: launchArgs }); newPage The newPage() function creates and returns a new Playwright page. Synthetics automatically sets up a Chrome DevTools Protocol (CDP) connection to enable network captures for HTTP archive (HAR) generation. Usage Use newPage() in either of the following ways: 1. Creating a new page in a new browser context: const page = await synthetics.newPage(browser); 2. Creating a new page in a specified browser context: // Create a new browser context const browserContext = await browser.newContext(); // Create a new page in the specified browser context const page = await synthetics.newPage(browserContext) Arguments Accepts either Playwright Browser instance or Playwright BrowserContext instance. Returns Promise <Page> where Page is a Playwright Page instance. close Closes the currently-opened browser. Usage Creating a canary 1709 Amazon CloudWatch User Guide await synthetics.close(); It is recommended to close the browser in a finally block of your script. Arguments None Returns Returns Promise<void> used by the Synthetics launch function for launching the browser. getDefaultLaunchOptions The getDefaultLaunchOptions() function returns the browser launch options that are used by CloudWatch Synthetics. Usage const defaultOptions = await synthetics.getDefaultLaunchOptions(); Arguments None Returns Returns Playwright launch options used by the Synthetics launch function for launching the browser. executeStep The executeStep function is used to execute a step in a Synthetics script. In CloudWatch Synthetics, a Synthetics step is a way to break down your canary script into a series of clearly defined actions, allowing you to monitor different parts of your application journey separately. For each step, CloudWatch Synthetics does the following: • Automatically captures a screenshot before step starts and after a step is complete. You can also capture screenshots inside a step. Screenshots are captured by default, but can be turned off by using Synthetics configurations (Todo: Link). • A report, including a summary, of step execution details like the duration of a step, pass or fail status, source and destination page URLs, associated screenshots, etc. is created for each canary Creating a canary 1710 Amazon CloudWatch User Guide run. When you choose a run in the CloudWatch Synthetics console, you can view execution details of each step on the Step tab. • SuccessPercent and Duration CloudWatch metrics are emitted for each step, enabling users to monitor availability and latency of each step. Usage await synthetics.executeStep("mystepname", async function () { await page.goto(url, { waitUntil: 'load', timeout: 30000 }); } Note Steps should run sequentially. Be sure to use await on promises. Arguments • stepName string (required) (boolean)— Name of the Synthetics step. • functionToExecute async function (required)— The function that you want Synthetics to run. This function should contain the logic for the step. • stepConfig object (optional)— Step configuration overrides the global Synthetics configuration for this step. • continueOnStepFailure boolean (optional) — Whether to continue running the canary script after this step fails. • screenshotOnStepStart boolean (optional) — Whether to take a
acw-ug-459
acw-ug.pdf
459
Usage await synthetics.executeStep("mystepname", async function () { await page.goto(url, { waitUntil: 'load', timeout: 30000 }); } Note Steps should run sequentially. Be sure to use await on promises. Arguments • stepName string (required) (boolean)— Name of the Synthetics step. • functionToExecute async function (required)— The function that you want Synthetics to run. This function should contain the logic for the step. • stepConfig object (optional)— Step configuration overrides the global Synthetics configuration for this step. • continueOnStepFailure boolean (optional) — Whether to continue running the canary script after this step fails. • screenshotOnStepStart boolean (optional) — Whether to take a screenshot at the start of this step. • screenshotOnStepSuccess boolean (optional) — Whether to take a screenshot if this step succeeds. • screenshotOnStepFailure boolean (optional) — Whether to take a screenshot if this step fails. • page — Playwright page object (optional) A Playwright page object. Synthetics uses this page object to capture screenshots and URLs. By default, Synthetics uses the Playwright page created when the synthetics.newPage() function is called for capturing page details like screenshots and URLs. Creating a canary 1711 Amazon CloudWatch Returns User Guide Returns a Promise that resolves with the value returned by the functionToExecute function. For an example script, see Sample code for canary scripts in this guide. Library functions available for Node.js canary scripts using Puppeteer This section describes the library functions available for Node.js canary scripts. Topics • Node.js library classes and functions that apply to all canaries • Node.js library classes and functions that apply to UI canaries only • Node.js library classes and functions that apply to API canaries only Node.js library classes and functions that apply to all canaries The following CloudWatch Synthetics library functions for Node.js are useful for all canaries. Topics • Synthetics class • SyntheticsConfiguration class • Synthetics logger • SyntheticsLogHelper class Synthetics class The following functions for all canaries are in the Synthetics class. Topics • addExecutionError(errorMessage, ex); • getCanaryName(); • getCanaryArn(); • getCanaryUserAgentString(); • getRuntimeVersion(); • getLogLevel(); Creating a canary 1712 Amazon CloudWatch • setLogLevel(); User Guide addExecutionError(errorMessage, ex); errorMessage describes the error and ex is the exception that is encountered You can use addExecutionError to set execution errors for your canary. It fails the canary without interrupting the script execution. It also doesn't impact your successPercent metrics. You should track errors as execution errors only if they are not important to indicate the success or failure of your canary script. An example of the use of addExecutionError is the following. You are monitoring the availability of your endpoint and taking screenshots after the page has loaded. Because the failure of taking a screenshot doesn't determine availability of the endpoint, you can catch any errors encountered while taking screenshots and add them as execution errors. Your availability metrics will still indicate that the endpoint is up and running, but your canary status will be marked as failed. The following sample code block catches such an error and adds it as an execution error. try { await synthetics.takeScreenshot(stepName, "loaded"); } catch(ex) { synthetics.addExecutionError('Unable to take screenshot ', ex); } getCanaryName(); Returns the name of the canary. getCanaryArn(); Returns the ARN of the canary. getCanaryUserAgentString(); Returns the custom user agent of the canary. getRuntimeVersion(); This function is available in runtime version syn-nodejs-puppeteer-3.0 and later. It returns the Synthetics runtime version of the canary. For example, the return value could be syn-nodejs- puppeteer-3.0. Creating a canary 1713 Amazon CloudWatch getLogLevel(); User Guide Retrieves the current log level for the Synthetics library. Possible values are the following: • 0 – Debug • 1 – Info • 2 – Warn • 3 – Error Example: let logLevel = synthetics.getLogLevel(); setLogLevel(); Sets the log level for the Synthetics library. Possible values are the following: • 0 – Debug • 1 – Info • 2 – Warn • 3 – Error Example: synthetics.setLogLevel(0); SyntheticsConfiguration class This class is available only in the syn-nodejs-2.1 runtime version or later. You can use the SyntheticsConfiguration class to configure the behavior of Synthetics library functions. For example, you can use this class to configure the executeStep() function to not capture screenshots. You can set CloudWatch Synthetics configurations at the global level, which are applied to all steps of canaries. You can also override these configurations at the step level by passing configuration key and value pairs. Creating a canary 1714 Amazon CloudWatch User Guide You can pass in options at the step level. For examples, see async executeStep(stepName, functionToExecute, [stepConfig]); and executeHttpStep(stepName, requestOptions, [callback], [stepConfig]) Topics • setConfig(options) • Visual monitoring setConfig(options) options is an object, which is a set of configurable options for your canary. The following sections explain the possible fields in options. setConfig(options) for all canaries For canaries using syn-nodejs-puppeteer-3.2 or later, the (options) for setConfig can include the following parameters: • includeRequestHeaders
acw-ug-460
acw-ug.pdf
460
steps of canaries. You can also override these configurations at the step level by passing configuration key and value pairs. Creating a canary 1714 Amazon CloudWatch User Guide You can pass in options at the step level. For examples, see async executeStep(stepName, functionToExecute, [stepConfig]); and executeHttpStep(stepName, requestOptions, [callback], [stepConfig]) Topics • setConfig(options) • Visual monitoring setConfig(options) options is an object, which is a set of configurable options for your canary. The following sections explain the possible fields in options. setConfig(options) for all canaries For canaries using syn-nodejs-puppeteer-3.2 or later, the (options) for setConfig can include the following parameters: • includeRequestHeaders (boolean)— Whether to include request headers in the report. The default is false. • includeResponseHeaders (boolean)— Whether to include response headers in the report. The default is false. • restrictedHeaders (array)— A list of header values to ignore, if headers are included. This applies to both request and response headers. For example, you can hide your credentials by passing includeRequestHeaders as true and restrictedHeaders as ['Authorization']. • includeRequestBody (boolean)— Whether to include the request body in the report. The default is false. • includeResponseBody (boolean)— Whether to include the response body in the report. The default is false. If you enable either includeResponseBody or logResponseBody, the data object is not returned in the response from some APIs, such as aws-sdk v3 clients. This is because of a limitation of Node.js and the type of response object used. setConfig(options) regarding CloudWatch metrics Creating a canary 1715 Amazon CloudWatch User Guide For canaries using syn-nodejs-puppeteer-3.1 or later, the (options) for setConfig can include the following Boolean parameters that determine which metrics are published by the canary. The default for each of these options is true. The options that start with aggregated determine whether the metric is emitted without the CanaryName dimension. You can use these metrics to see the aggregated results for all of your canaries. The other options determine whether the metric is emitted with the CanaryName dimension. You can use these metrics to see results for each individual canary. For a list of CloudWatch metrics emitted by canaries, see CloudWatch metrics published by canaries. • failedCanaryMetric (boolean)— Whether to emit the Failed metric (with the CanaryName dimension) for this canary. The default is true. • failedRequestsMetric (boolean)— Whether to emit the Failed requests metric (with the CanaryName dimension) for this canary. The default is true. • _2xxMetric (boolean)— Whether to emit the 2xx metric (with the CanaryName dimension) for this canary. The default is true. • _4xxMetric (boolean)— Whether to emit the 4xx metric (with the CanaryName dimension) for this canary. The default is true. • _5xxMetric (boolean)— Whether to emit the 5xx metric (with the CanaryName dimension) for this canary. The default is true. • stepDurationMetric (boolean)— Whether to emit the Step duration metric (with the CanaryName StepName dimensions) for this canary. The default is true. • stepSuccessMetric (boolean)— Whether to emit the Step success metric (with the CanaryName StepName dimensions) for this canary. The default is true. • aggregatedFailedCanaryMetric (boolean)— Whether to emit the Failed metric (without the CanaryName dimension) for this canary. The default is true. • aggregatedFailedRequestsMetric (boolean)— Whether to emit the Failed Requests metric (without the CanaryName dimension) for this canary. The default is true. • aggregated2xxMetric (boolean)— Whether to emit the 2xx metric (without the CanaryName dimension) for this canary. The default is true. • aggregated4xxMetric (boolean)— Whether to emit the 4xx metric (without the CanaryName dimension) for this canary. The default is true. • aggregated5xxMetric (boolean)— Whether to emit the 5xx metric (without the CanaryName dimension) for this canary. The default is true. Creating a canary 1716 Amazon CloudWatch User Guide • visualMonitoringSuccessPercentMetric (boolean)— Whether to emit the visualMonitoringSuccessPercent metric for this canary. The default is true. • visualMonitoringTotalComparisonsMetric (boolean)— Whether to emit the visualMonitoringTotalComparisons metric for this canary. The default is false. • includeUrlPassword (boolean)— Whether to include a password that appears in the URL. By default, passwords that appear in URLs are redacted from logs and reports, to prevent disclosing sensitive data. The default is false. • restrictedUrlParameters (array)— A list of URL path or query parameters to redact. This applies to URLs appearing in logs, reports, and errors. The parameter is case-insensitive. You can pass an asterisk (*) as a value to redact all URL path and query parameter values. The default is an empty array. • logRequest (boolean)— Whether to log every request in canary logs. For UI canaries, this logs each request sent by the browser. The default is true. • logResponse (boolean)— Whether to log every response in canary logs. For UI canaries, this logs every response received by the browser. The default is true. • logRequestBody (boolean)— Whether to log request bodies along with the requests in canary logs. This configuration applies only if logRequest is
acw-ug-461
acw-ug.pdf
461
is case-insensitive. You can pass an asterisk (*) as a value to redact all URL path and query parameter values. The default is an empty array. • logRequest (boolean)— Whether to log every request in canary logs. For UI canaries, this logs each request sent by the browser. The default is true. • logResponse (boolean)— Whether to log every response in canary logs. For UI canaries, this logs every response received by the browser. The default is true. • logRequestBody (boolean)— Whether to log request bodies along with the requests in canary logs. This configuration applies only if logRequest is true. The default is false. • logResponseBody (boolean)— Whether to log response bodies along with the responses in canary logs. This configuration applies only if logResponse is true. The default is false. If you enable either includeResponseBody or logResponseBody, the data object is not returned in the response from some APIs, such as aws-sdk v3 clients. This is because of a limitation of Node.js and the type of response object used. • logRequestHeaders (boolean)— Whether to log request headers along with the requests in canary logs. This configuration applies only if logRequest is true. The default is false. Note that includeRequestHeaders enables headers in artifacts. • logResponseHeaders (boolean)— Whether to log response headers along with the responses in canary logs. This configuration applies only if logResponse is true. The default is false. Note that includeResponseHeaders enables headers in artifacts. Creating a canary 1717 Amazon CloudWatch Note User Guide The Duration and SuccessPercent metrics are always emitted for each canary, both with and without the CanaryName metric. Methods to enable or disable metrics disableAggregatedRequestMetrics() Disables the canary from emitting all request metrics that are emitted with no CanaryName dimension. disableRequestMetrics() Disables all request metrics, including both per-canary metrics and metrics aggregated across all canaries. disableStepMetrics() Disables all step metrics, including both step success metrics and step duration metrics. enableAggregatedRequestMetrics() Enables the canary to emit all request metrics that are emitted with no CanaryName dimension. enableRequestMetrics() Enables all request metrics, including both per-canary metrics and metrics aggregated across all canaries. enableStepMetrics() Enables all step metrics, including both step success metrics and step duration metrics. get2xxMetric() Returns whether the canary emits a 2xx metric with the CanaryName dimension. get4xxMetric() Returns whether the canary emits a 4xx metric with the CanaryName dimension. Creating a canary 1718 Amazon CloudWatch get5xxMetric() User Guide Returns whether the canary emits a 5xx metric with the CanaryName dimension. getAggregated2xxMetric() Returns whether the canary emits a 2xx metric with no dimension. getAggregated4xxMetric() Returns whether the canary emits a 4xx metric with no dimension. getAggregatedFailedCanaryMetric() Returns whether the canary emits a Failed metric with no dimension. getAggregatedFailedRequestsMetric() Returns whether the canary emits a Failed requests metric with no dimension. getAggregated5xxMetric() Returns whether the canary emits a 5xx metric with no dimension. getFailedCanaryMetric() Returns whether the canary emits a Failed metric with the CanaryName dimension. getFailedRequestsMetric() Returns whether the canary emits a Failed requests metric with the CanaryName dimension. getStepDurationMetric() Returns whether the canary emits a Duration metric with the CanaryName dimension for this canary. getStepSuccessMetric() Returns whether the canary emits a StepSuccess metric with the CanaryName dimension for this canary. Creating a canary 1719 Amazon CloudWatch with2xxMetric(_2xxMetric) User Guide Accepts a Boolean argument, which specifies whether to emit a 2xx metric with the CanaryName dimension for this canary. with4xxMetric(_4xxMetric) Accepts a Boolean argument, which specifies whether to emit a 4xx metric with the CanaryName dimension for this canary. with5xxMetric(_5xxMetric) Accepts a Boolean argument, which specifies whether to emit a 5xx metric with the CanaryName dimension for this canary. withAggregated2xxMetric(aggregated2xxMetric) Accepts a Boolean argument, which specifies whether to emit a 2xx metric with no dimension for this canary. withAggregated4xxMetric(aggregated4xxMetric) Accepts a Boolean argument, which specifies whether to emit a 4xx metric with no dimension for this canary. withAggregated5xxMetric(aggregated5xxMetric) Accepts a Boolean argument, which specifies whether to emit a 5xx metric with no dimension for this canary. withAggregatedFailedCanaryMetric(aggregatedFailedCanaryMetric) Accepts a Boolean argument, which specifies whether to emit a Failed metric with no dimension for this canary. withAggregatedFailedRequestsMetric(aggregatedFailedRequestsMetric) Accepts a Boolean argument, which specifies whether to emit a Failed requests metric with no dimension for this canary. withFailedCanaryMetric(failedCanaryMetric) Creating a canary 1720 Amazon CloudWatch User Guide Accepts a Boolean argument, which specifies whether to emit a Failed metric with the CanaryName dimension for this canary. withFailedRequestsMetric(failedRequestsMetric) Accepts a Boolean argument, which specifies whether to emit a Failed requests metric with the CanaryName dimension for this canary. withStepDurationMetric(stepDurationMetric) Accepts a Boolean argument, which specifies whether to emit a Duration metric with the CanaryName dimension for this canary. withStepSuccessMetric(stepSuccessMetric) Accepts a Boolean argument, which specifies whether to emit a StepSuccess metric with the CanaryName dimension for this canary. Methods to enable or disable other features withHarFile() Accepts a Boolean argument, which specifies whether to create a
acw-ug-462
acw-ug.pdf
462
User Guide Accepts a Boolean argument, which specifies whether to emit a Failed metric with the CanaryName dimension for this canary. withFailedRequestsMetric(failedRequestsMetric) Accepts a Boolean argument, which specifies whether to emit a Failed requests metric with the CanaryName dimension for this canary. withStepDurationMetric(stepDurationMetric) Accepts a Boolean argument, which specifies whether to emit a Duration metric with the CanaryName dimension for this canary. withStepSuccessMetric(stepSuccessMetric) Accepts a Boolean argument, which specifies whether to emit a StepSuccess metric with the CanaryName dimension for this canary. Methods to enable or disable other features withHarFile() Accepts a Boolean argument, which specifies whether to create a HAR file for this canary. withStepsReport() Accepts a Boolean argument, which specifies whether to report a step execution summary for this canary. withIncludeUrlPassword() Accepts a Boolean argument, which specifies whether to include passwords that appear in URLs in logs and reports. withRestrictedUrlParameters() Accepts an array of URL path or query parameters to redact. This applies to URLs appearing in logs, reports, and errors. You can pass an asterisk (*) as a value to redact all URL path and query parameter values withLogRequest() Creating a canary 1721 Amazon CloudWatch User Guide Accepts a Boolean argument, which specifies whether to log every request in the canary's logs. withLogResponse() Accepts a Boolean argument, which specifies whether to log every response in the canary's logs. withLogRequestBody() Accepts a Boolean argument, which specifies whether to log every request body in the canary's logs. withLogResponseBody() Accepts a Boolean argument, which specifies whether to log every response body in the canary's logs. withLogRequestHeaders() Accepts a Boolean argument, which specifies whether to log every request header in the canary's logs. withLogResponseHeaders() Accepts a Boolean argument, which specifies whether to log every response header in the canary's logs. getHarFile() Returns whether the canary creates a HAR file. getStepsReport() Returns whether the canary reports a step execution summary. getIncludeUrlPassword() Returns whether the canary includes passwords that appear in URLs in logs and reports. getRestrictedUrlParameters() Returns whether the canary redacts URL path or query parameters. Creating a canary 1722 Amazon CloudWatch getLogRequest() User Guide Returns whether the canary logs every request in the canary's logs. getLogResponse() Returns whether the canary logs every response in the canary's logs. getLogRequestBody() Returns whether the canary logs every request body in the canary's logs. getLogResponseBody() Returns whether the canary logs every response body in the canary's logs. getLogRequestHeaders() Returns whether the canary logs every request header in the canary's logs. getLogResponseHeaders() Returns whether the canary logs every response header in the canary's logs. Functions for all canaries • withIncludeRequestHeaders(includeRequestHeaders) • withIncludeResponseHeaders(includeResponseHeaders) • withRestrictedHeaders(restrictedHeaders) • withIncludeRequestBody(includeRequestBody) • withIncludeResponseBody(includeResponseBody) • enableReportingOptions()— Enables all reporting options-- includeRequestHeaders, includeResponseHeaders, includeRequestBody, and includeResponseBody, . • disableReportingOptions()— Disables all reporting options-- includeRequestHeaders, includeResponseHeaders, includeRequestBody, and includeResponseBody, . setConfig(options) for UI canaries For UI canaries, setConfig can include the following Boolean parameters: Creating a canary 1723 Amazon CloudWatch User Guide • continueOnStepFailure (boolean)— Whether to continue with running the canary script after a step fails (this refers to the executeStep function). If any steps fail, the canary run will still be marked as failed. The default is false. • harFile (boolean)— Whether to create a HAR file. The default is True. • screenshotOnStepStart (boolean)— Whether to take a screenshot before starting a step. • screenshotOnStepSuccess (boolean)— Whether to take a screenshot after completing a successful step. • screenshotOnStepFailure (boolean)— Whether to take a screenshot after a step fails. Methods to enable or disable screenshots disableStepScreenshots() Disables all screenshot options (screenshotOnStepStart, screenshotOnStepSuccess, and screenshotOnStepFailure). enableStepScreenshots() Enables all screenshot options (screenshotOnStepStart, screenshotOnStepSuccess, and screenshotOnStepFailure). By default, all these methods are enabled. getScreenshotOnStepFailure() Returns whether the canary takes a screenshot after a step fails. getScreenshotOnStepStart() Returns whether the canary takes a screenshot before starting a step. getScreenshotOnStepSuccess() Returns whether the canary takes a screenshot after completing a step successfully. withScreenshotOnStepStart(screenshotOnStepStart) Accepts a Boolean argument, which indicates whether to take a screenshot before starting a step. withScreenshotOnStepSuccess(screenshotOnStepSuccess) Accepts a Boolean argument, which indicates whether to take a screenshot after completing a step successfully. Creating a canary 1724 Amazon CloudWatch User Guide withScreenshotOnStepFailure(screenshotOnStepFailure) Accepts a Boolean argument, which indicates whether to take a screenshot after a step fails. Usage in UI canaries First, import the synthetics dependency and fetch the configuration. // Import Synthetics dependency const synthetics = require('Synthetics'); // Get Synthetics configuration const synConfig = synthetics.getConfiguration(); Then, set the configuration for each option by calling the setConfig method using one of the following options. // Set configuration values synConfig.setConfig({ screenshotOnStepStart: true, screenshotOnStepSuccess: false, screenshotOnStepFailure: false }); Or synConfig.withScreenshotOnStepStart(false).withScreenshotOnStepSuccess(true).withScreenshotOnStepFailure(true) To disable all screenshots, use the disableStepScreenshots() function as in this example. synConfig.disableStepScreenshots(); You can enable and disable screenshots at any point in the code. For example, to disable screenshots only for one step, disable them before running that step and then enable them after the step. setConfig(options)
acw-ug-463
acw-ug.pdf
463
and fetch the configuration. // Import Synthetics dependency const synthetics = require('Synthetics'); // Get Synthetics configuration const synConfig = synthetics.getConfiguration(); Then, set the configuration for each option by calling the setConfig method using one of the following options. // Set configuration values synConfig.setConfig({ screenshotOnStepStart: true, screenshotOnStepSuccess: false, screenshotOnStepFailure: false }); Or synConfig.withScreenshotOnStepStart(false).withScreenshotOnStepSuccess(true).withScreenshotOnStepFailure(true) To disable all screenshots, use the disableStepScreenshots() function as in this example. synConfig.disableStepScreenshots(); You can enable and disable screenshots at any point in the code. For example, to disable screenshots only for one step, disable them before running that step and then enable them after the step. setConfig(options) for API canaries For API canaries, setConfig can include the following Boolean parameters: Creating a canary 1725 Amazon CloudWatch User Guide • continueOnHttpStepFailure (boolean)— Whether to continue with running the canary script after an HTTP step fails (this refers to the executeHttpStep function). If any steps fail, the canary run will still be marked as failed. The default is true. Visual monitoring Visual monitoring compares screenshots taken during a canary run with screenshots taken during a baseline canary run. If the discrepancy between the two screenshots is beyond a threshold percentage, the canary fails and you can see the areas with differences highlighted in color in the canary run report. Visual monitoring is supported in canaries running syn-puppeteer-node-3.2 and later. It is not currently supported in canaries running Python and Selenium. To enable visual monitoring, add the following line of code to the canary script. For more details, see SyntheticsConfiguration class. syntheticsConfiguration.withVisualCompareWithBaseRun(true); The first time that the canary runs successfully after this line is added to the script, it uses the screenshots taken during that run as the baseline for comparison. After that first canary run, you can use the CloudWatch console to edit the canary to do any of the following: • Set the next run of the canary as the new baseline. • Draw boundaries on the current baseline screenshot to designate areas of the screenshot to ignore during visual comparisons. • Remove a screenshot from being used for visual monitoring. For more information about using the CloudWatch console to edit a canary, see Edit or delete a canary. Other options for visual monitoring syntheticsConfiguration.withVisualVarianceThresholdPercentage(desiredPercentage) Set the acceptable percentage for screenshot variance in visual comparisons. syntheticsConfiguration.withVisualVarianceHighlightHexColor("#fafa00") Set the highlight color that designates variance areas when you look at canary run reports that use visual monitoring. Creating a canary 1726 Amazon CloudWatch User Guide syntheticsConfiguration.withFailCanaryRunOnVisualVariance(failCanary) Set whether or not the canary fails when there is a visual difference that is more than the threshold. The default is to fail the canary. Synthetics logger SyntheticsLogger writes logs out to both the console and to a local log file at the same log level. This log file is written to both locations only if the log level is at or below the desired logging level of the log function that was called. The logging statements in the local log file are prepended with "DEBUG: ", "INFO: ", and so on to match the log level of the function that was called. You can use the SyntheticsLogger, assuming you want to run the Synthetics Library at the same log level as your Synthetics canary logging. Using the SyntheticsLogger is not required to create a log file that is uploaded to your S3 results location. You could instead create a different log file in the /tmp folder. Any files created under the /tmp folder are uploaded to the results location in S3 as artifacts. To use the Synthetics Library logger: const log = require('SyntheticsLogger'); Useful function definitions: log.debug(message, ex); Parameters: message is the message to log. ex is the exception, if any, to log. Example: log.debug("Starting step - login."); log.error(message, ex); Parameters: message is the message to log. ex is the exception, if any, to log. Example: Creating a canary 1727 User Guide Amazon CloudWatch try { await login(); catch (ex) { log.error("Error encountered in step - login.", ex); } log.info(message, ex); Parameters: message is the message to log. ex is the exception, if any, to log. Example: log.info("Successfully completed step - login."); log.log(message, ex); This is an alias for log.info. Parameters: message is the message to log. ex is the exception, if any, to log. Example: log.log("Successfully completed step - login."); log.warn(message, ex); Parameters: message is the message to log. ex is the exception, if any, to log. Example: log.warn("Exception encountered trying to publish CloudWatch Metric.", ex); SyntheticsLogHelper class The SyntheticsLogHelper class is available in the runtime syn-nodejs-puppeteer-3.2 and later runtimes. It is already initialized in the CloudWatch Synthetics library and is configured with Synthetics configuration. You can add this as a dependency in your script. This class enables you to sanitize URLs, headers, and error messages to redact sensitive information. Creating a canary 1728 Amazon CloudWatch Note User Guide Synthetics sanitizes
acw-ug-464
acw-ug.pdf
464
any, to log. Example: log.log("Successfully completed step - login."); log.warn(message, ex); Parameters: message is the message to log. ex is the exception, if any, to log. Example: log.warn("Exception encountered trying to publish CloudWatch Metric.", ex); SyntheticsLogHelper class The SyntheticsLogHelper class is available in the runtime syn-nodejs-puppeteer-3.2 and later runtimes. It is already initialized in the CloudWatch Synthetics library and is configured with Synthetics configuration. You can add this as a dependency in your script. This class enables you to sanitize URLs, headers, and error messages to redact sensitive information. Creating a canary 1728 Amazon CloudWatch Note User Guide Synthetics sanitizes all URLs and error messages it logs before including them in logs, reports, HAR files, and canary run errors based on the Synthetics configuration setting restrictedUrlParameters. You have to use getSanitizedUrl or getSanitizedErrorMessage only if you are logging URLs or errors in your script. Synthetics does not store any canary artifacts except for canary errors thrown by the script. Canary run artifacts are stored in your customer account. For more information, see Security considerations for Synthetics canaries. Topics • getSanitizedUrl(url, stepConfig = null) • getSanitizedErrorMessage • getSanitizedHeaders(headers, stepConfig=null) getSanitizedUrl(url, stepConfig = null) This function is available in syn-nodejs-puppeteer-3.2 and later. It returns sanitized url strings based on the configuration. You can choose to redact sensitive URL parameters such as password and access_token by setting the property restrictedUrlParameters. By default, passwords in URLs are redacted. You can enable URL passwords if needed by setting includeUrlPassword to true. This function throws an error if the URL passed in is not a valid URL. Parameters • url is a string and is the URL to sanitize. • stepConfig (Optional) overrides the global Synthetics configuration for this function. If stepConfig is not passed in, the global configuration is used to sanitize the URL. Example This example uses the following sample URL: https://example.com/learn/home? access_token=12345&token_type=Bearer&expires_in=1200. In this example, Creating a canary 1729 Amazon CloudWatch User Guide access_token contains your sensitive information which shouldn't be logged. Note that the Synthetics services doesn't store any canary run artifacts. Artifacts such as logs, screenshots, and reports are all stored in an Amazon S3 bucket in your customer account. The first step is to set the Synthetics configuration. // Import Synthetics dependency const synthetics = require('Synthetics'); // Import Synthetics logger for logging url const log = require('SyntheticsLogger'); // Get Synthetics configuration const synConfig = synthetics.getConfiguration(); // Set restricted parameters synConfig.setConfig({ restrictedUrlParameters: ['access_token']; }); // Import SyntheticsLogHelper dependency const syntheticsLogHelper = require('SyntheticsLogHelper'); const sanitizedUrl = syntheticsLogHelper.getSanitizedUrl('URL'); const urlConfig = { restrictedUrlParameters = ['*'] }; const sanitizedUrl = syntheticsLogHelper.getSanitizedUrl('URL', urlConfig); logger.info('My example url is: ' + sanitizedUrl); Next, sanitize and log the URL // Import SyntheticsLogHelper dependency const syntheticsLogHelper = require('SyntheticsLogHelper'); const sanitizedUrl = syntheticsLogHelper.getSanitizedUrl('https://example.com/learn/ home?access_token=12345&token_type=Bearer&expires_in=1200'); This logs the following in your canary log. Creating a canary 1730 Amazon CloudWatch User Guide My example url is: https://example.com/learn/home? access_token=REDACTED&token_type=Bearer&expires_in=1200 You can override the Synthetics configuration for a URL by passing in an optional parameter containing Synthetics configuration options, as in the following example. const urlConfig = { restrictedUrlParameters = ['*'] }; const sanitizedUrl = syntheticsLogHelper.getSanitizedUrl('https://example.com/learn/ home?access_token=12345&token_type=Bearer&expires_in=1200', urlConfig); logger.info('My example url is: ' + sanitizedUrl); The preceding example redacts all query parameters, and is logged as follows: My example url is: https://example.com/learn/home? access_token=REDACTED&token_type=REDACTED&expires_in=REDACTED getSanitizedErrorMessage This function is available in syn-nodejs-puppeteer-3.2 and later. It returns sanitized error strings by sanitizing any URLs present based on the Synthetics configuration. You can choose to override the global Synthetics configuration when you call this function by passing an optional stepConfig parameter. Parameters • error is the error to sanitize. It can be an Error object or a string. • stepConfig (Optional) overrides the global Synthetics configuration for this function. If stepConfig is not passed in, the global configuration is used to sanitize the URL. Example This example uses the following error: Failed to load url: https://example.com/ learn/home?access_token=12345&token_type=Bearer&expires_in=1200 The first step is to set the Synthetics configuration. // Import Synthetics dependency const synthetics = require('Synthetics'); Creating a canary 1731 Amazon CloudWatch User Guide // Import Synthetics logger for logging url const log = require('SyntheticsLogger'); // Get Synthetics configuration const synConfig = synthetics.getConfiguration(); // Set restricted parameters synConfig.setConfig({ restrictedUrlParameters: ['access_token']; }); Next, sanitize and log the error message // Import SyntheticsLogHelper dependency const syntheticsLogHelper = require('SyntheticsLogHelper'); try { // Your code which can throw an error containing url which your script logs } catch (error) { const sanitizedErrorMessage = syntheticsLogHelper.getSanitizedErrorMessage(errorMessage); logger.info(sanitizedErrorMessage); } This logs the following in your canary log. Failed to load url: https://example.com/learn/home? access_token=REDACTED&token_type=Bearer&expires_in=1200 getSanitizedHeaders(headers, stepConfig=null) This function is available in syn-nodejs-puppeteer-3.2 and later. It returns sanitized headers based on the restrictedHeaders property of syntheticsConfiguration. The headers specified in the restrictedHeaders property are redacted from logs, HAR files, and reports. Parameters • headers is an object containing the headers to sanitize. • stepConfig (Optional) overrides the global Synthetics
acw-ug-465
acw-ug.pdf
465
SyntheticsLogHelper dependency const syntheticsLogHelper = require('SyntheticsLogHelper'); try { // Your code which can throw an error containing url which your script logs } catch (error) { const sanitizedErrorMessage = syntheticsLogHelper.getSanitizedErrorMessage(errorMessage); logger.info(sanitizedErrorMessage); } This logs the following in your canary log. Failed to load url: https://example.com/learn/home? access_token=REDACTED&token_type=Bearer&expires_in=1200 getSanitizedHeaders(headers, stepConfig=null) This function is available in syn-nodejs-puppeteer-3.2 and later. It returns sanitized headers based on the restrictedHeaders property of syntheticsConfiguration. The headers specified in the restrictedHeaders property are redacted from logs, HAR files, and reports. Parameters • headers is an object containing the headers to sanitize. • stepConfig (Optional) overrides the global Synthetics configuration for this function. If stepConfig is not passed in, the global configuration is used to sanitize the headers. Creating a canary 1732 Amazon CloudWatch User Guide Node.js library classes and functions that apply to UI canaries only The following CloudWatch Synthetics library functions for Node.js are useful only for UI canaries. Topics • Synthetics class • BrokenLinkCheckerReport class • SyntheticsLink class Synthetics class The following functions are in the Synthetics class. Topics • async addUserAgent(page, userAgentString); • async executeStep(stepName, functionToExecute, [stepConfig]); • getDefaultLaunchOptions(); • getPage(); • getRequestResponseLogHelper(); • launch(options) • RequestResponseLogHelper class • setRequestResponseLogHelper(); • async takeScreenshot(name, suffix); async addUserAgent(page, userAgentString); This function appends userAgentString to the specified page's user-agent header. Example: await synthetics.addUserAgent(page, "MyApp-1.0"); Results in the page’s user-agent header being set to browsers-user-agent-header- valueMyApp-1.0 Creating a canary 1733 Amazon CloudWatch User Guide async executeStep(stepName, functionToExecute, [stepConfig]); Executes the provided step, wrapping it with start/pass/fail logging, start/pass/fail screenshots, and pass/fail and duration metrics. Note If you are using the syn-nodejs-2.1 or later runtime, you can configure whether and when screenshots are taken. For more information, see SyntheticsConfiguration class. The executeStep function also does the following: • Logs that the step started. • Takes a screenshot named <stepName>-starting. • Starts a timer. • Executes the provided function. • If the function returns normally, it counts as passing. If the function throws, it counts as failing. • Ends the timer. • Logs whether the step passed or failed • Takes a screenshot named <stepName>-succeeded or <stepName>-failed. • Emits the stepName SuccessPercent metric, 100 for pass or 0 for failure. • Emits the stepName Duration metric, with a value based on the step start and end times. • Finally, returns what the functionToExecute returned or re-throws what functionToExecute threw. If the canary uses the syn-nodejs-2.0 runtime or later, this function also adds a step execution summary to the canary's report. The summary includes details about each step, such as start time, end time, status (PASSED/FAILED), failure reason (if failed), and screenshots captured during the execution of each step. Example: await synthetics.executeStep('navigateToUrl', async function (timeoutInMillis = 30000) { Creating a canary 1734 Amazon CloudWatch User Guide await page.goto(url, {waitUntil: ['load', 'networkidle0'], timeout: timeoutInMillis});}); Response: Returns what functionToExecute returns. Updates with syn-nodejs-2.2 Starting with syn-nodejs-2.2, you can optionally pass step configurations to override CloudWatch Synthetics configurations at the step level. For a list of options that you can pass to executeStep, see SyntheticsConfiguration class. The following example overrides the default false configuration for continueOnStepFailure to true and specifies when to take screenthots. var stepConfig = { 'continueOnStepFailure': true, 'screenshotOnStepStart': false, 'screenshotOnStepSuccess': true, 'screenshotOnStepFailure': false } await executeStep('Navigate to amazon', async function (timeoutInMillis = 30000) { await page.goto(url, {waitUntil: ['load', 'networkidle0'], timeout: timeoutInMillis}); }, stepConfig); getDefaultLaunchOptions(); The getDefaultLaunchOptions() function returns the browser launch options that are used by CloudWatch Synthetics. For more information, see Launch options type // This function returns default launch options used by Synthetics. const defaultOptions = await synthetics.getDefaultLaunchOptions(); getPage(); Returns the current open page as a Puppeteer object. For more information, see Puppeteer API v1.14.0. Creating a canary 1735 Amazon CloudWatch Example: let page = await synthetics.getPage(); Response: User Guide The page (Puppeteer object) that is currently open in the current browser session. getRequestResponseLogHelper(); Important In canaries that use the syn-nodejs-puppeteer-3.2 runtime or later, this function is deprecated along with the RequestResponseLogHelper class. Any use of this function causes a warning to appear in your canary logs. This function will be removed in future runtime versions. If you are using this function, use RequestResponseLogHelper class instead. Use this function as a builder pattern for tweaking the request and response logging flags. Example: synthetics.setRequestResponseLogHelper(getRequestResponseLogHelper().withLogRequestHeaders(false));; Response: {RequestResponseLogHelper} launch(options) The options for this function are available only in the syn-nodejs-2.1 runtime version or later. This function is used only for UI canaries. It closes the existing browser and launches a new one. Note CloudWatch Synthetics always launches a browser before starting to run your script. You don't need to call launch() unless you want to launch a new browser with custom options. Creating a canary 1736 Amazon CloudWatch User Guide (options) is a configurable set of options to set on the browser. For more information, Launch options type . If you call this
acw-ug-466
acw-ug.pdf
466
flags. Example: synthetics.setRequestResponseLogHelper(getRequestResponseLogHelper().withLogRequestHeaders(false));; Response: {RequestResponseLogHelper} launch(options) The options for this function are available only in the syn-nodejs-2.1 runtime version or later. This function is used only for UI canaries. It closes the existing browser and launches a new one. Note CloudWatch Synthetics always launches a browser before starting to run your script. You don't need to call launch() unless you want to launch a new browser with custom options. Creating a canary 1736 Amazon CloudWatch User Guide (options) is a configurable set of options to set on the browser. For more information, Launch options type . If you call this function with no options, Synthetics launches a browser with default arguments, executablePath, and defaultViewport. The default viewport in CloudWatch Synthetics is 1920 by 1080. You can override launch parameters used by CloudWatch Synthetics and pass additional parameters when launching the browser. For example, the following code snippet launches a browser with default arguments and a default executable path, but with a viewport of 800 x 600. await synthetics.launch({ defaultViewport: { "deviceScaleFactor": 1, "width": 800, "height": 600 }}); The following sample code adds a new ignoreHTTPSErrors parameter to the CloudWatch Synthetics launch parameters: await synthetics.launch({ ignoreHTTPSErrors: true }); You can disable web security by adding a --disable-web-security flag to args in the CloudWatch Synthetics launch parameters: // This function adds the --disable-web-security flag to the launch parameters const defaultOptions = await synthetics.getDefaultLaunchOptions(); const launchArgs = [...defaultOptions.args, '--disable-web-security']; await synthetics.launch({ args: launchArgs }); RequestResponseLogHelper class Important In canaries that use the syn-nodejs-puppeteer-3.2 runtime or later, this class is deprecated. Any use of this class causes a warning to appear in your canary logs. This Creating a canary 1737 Amazon CloudWatch User Guide function will be removed in future runtime versions. If you are using this function, use RequestResponseLogHelper class instead. Handles the fine-grained configuration and creation of string representations of request and response payloads. class RequestResponseLogHelper { constructor () { this.request = {url: true, resourceType: false, method: false, headers: false, postData: false}; this.response = {status: true, statusText: true, url: true, remoteAddress: false, headers: false}; } withLogRequestUrl(logRequestUrl); withLogRequestResourceType(logRequestResourceType); withLogRequestMethod(logRequestMethod); withLogRequestHeaders(logRequestHeaders); withLogRequestPostData(logRequestPostData); withLogResponseStatus(logResponseStatus); withLogResponseStatusText(logResponseStatusText); withLogResponseUrl(logResponseUrl); withLogResponseRemoteAddress(logResponseRemoteAddress); withLogResponseHeaders(logResponseHeaders); Example: synthetics.setRequestResponseLogHelper(getRequestResponseLogHelper() .withLogRequestPostData(true) .withLogRequestHeaders(true) Creating a canary 1738 Amazon CloudWatch User Guide .withLogResponseHeaders(true)); Response: {RequestResponseLogHelper} setRequestResponseLogHelper(); Important In canaries that use the syn-nodejs-puppeteer-3.2 runtime or later, this function is deprecated along with the RequestResponseLogHelper class. Any use of this function causes a warning to appear in your canary logs. This function will be removed in future runtime versions. If you are using this function, use RequestResponseLogHelper class instead. Use this function as a builder pattern for setting the request and response logging flags. Example: synthetics.setRequestResponseLogHelper().withLogRequestHeaders(true).withLogResponseHeaders(true); Response: {RequestResponseLogHelper} async takeScreenshot(name, suffix); Takes a screenshot (.PNG) of the current page with name and suffix (optional). Example: await synthetics.takeScreenshot("navigateToUrl", "loaded") This example captures and uploads a screenshot named 01-navigateToUrl-loaded.png to the canary's S3 bucket. Creating a canary 1739 Amazon CloudWatch User Guide You can take a screenshot for a particular canary step by passing the stepName as the first parameter. Screenshots are linked to the canary step in your reports, to help you track each step while debugging. CloudWatch Synthetics canaries automatically take screenshots before starting a step (the executeStep function) and after the step completion (unless you configure the canary to disable screenshots). You can take more screenshots by passing in the step name in the takeScreenshot function. The following example takes screenshot with the signupForm as the value of the stepName. The screenshot will be named 02-signupForm-address and will be linked to the step named signupForm in the canary report. await synthetics.takeScreenshot('signupForm', 'address') BrokenLinkCheckerReport class This class provides methods to add a synthetics link. It's supported only on canaries that use the syn-nodejs-2.0-beta version of the runtime or later. To use BrokenLinkCheckerReport, include the following lines in the script: const BrokenLinkCheckerReport = require('BrokenLinkCheckerReport'); const brokenLinkCheckerReport = new BrokenLinkCheckerReport(); Useful function definitions: addLink(syntheticsLink, isBroken) syntheticsLink is a SyntheticsLink object representing a link. This function adds the link according to the status code. By default, it considers a link to be broken if the status code is not available or the status code is 400 or higher. You can override this default behavior by passing in the optional parameter isBrokenLink with a value of true or false. This function does not have a return value. getLinks() This function returns an array of SyntheticsLink objects that are included in the broken link checker report. Creating a canary 1740 Amazon CloudWatch getTotalBrokenLinks() User Guide This function returns a number representing the total number of broken links. getTotalLinksChecked() This function returns a number representing the total number of links included in the report. How to use BrokenLinkCheckerReport The following canary script code snippet demonstrates an example of navigating to a link and adding it to the broken link checker report. 1. Import SyntheticsLink,
acw-ug-467
acw-ug.pdf
467
with a value of true or false. This function does not have a return value. getLinks() This function returns an array of SyntheticsLink objects that are included in the broken link checker report. Creating a canary 1740 Amazon CloudWatch getTotalBrokenLinks() User Guide This function returns a number representing the total number of broken links. getTotalLinksChecked() This function returns a number representing the total number of links included in the report. How to use BrokenLinkCheckerReport The following canary script code snippet demonstrates an example of navigating to a link and adding it to the broken link checker report. 1. Import SyntheticsLink, BrokenLinkCheckerReport, and Synthetics. const BrokenLinkCheckerReport = require('BrokenLinkCheckerReport'); const SyntheticsLink = require('SyntheticsLink'); // Synthetics dependency const synthetics = require('Synthetics'); 2. To add a link to the report, create an instance of BrokenLinkCheckerReport. let brokenLinkCheckerReport = new BrokenLinkCheckerReport(); 3. Navigate to the URL and add it to the broken link checker report. let url = "https://amazon.com"; let syntheticsLink = new SyntheticsLink(url); // Navigate to the url. let page = await synthetics.getPage(); // Create a new instance of Synthetics Link let link = new SyntheticsLink(url) try { const response = await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 30000}); } catch (ex) { // Add failure reason if navigation fails. link.withFailureReason(ex); Creating a canary 1741 Amazon CloudWatch } User Guide if (response) { // Capture screenshot of destination page let screenshotResult = await synthetics.takeScreenshot('amazon-home', 'loaded'); // Add screenshot result to synthetics link link.addScreenshotResult(screenshotResult); // Add status code and status description to the link link.withStatusCode(response.status()).withStatusText(response.statusText()) } // Add link to broken link checker report. brokenLinkCheckerReport.addLink(link); 4. Add the report to Synthetics. This creates a JSON file named BrokenLinkCheckerReport.json in your S3 bucket for each canary run. You can see a links report in the console for each canary run along with screenshots, logs, and HAR files. await synthetics.addReport(brokenLinkCheckerReport); SyntheticsLink class This class provides methods to wrap information. It's supported only on canaries that use the syn- nodejs-2.0-beta version of the runtime or later. To use SyntheticsLink, include the following lines in the script: const SyntheticsLink = require('SyntheticsLink'); const syntheticsLink = new SyntheticsLink("https://www.amazon.com"); This function returns syntheticsLinkObject Useful function definitions: withUrl(url) url is a URL string. This function returns syntheticsLinkObject withText(text) Creating a canary 1742 Amazon CloudWatch User Guide text is a string representing anchor text. This function returns syntheticsLinkObject. It adds anchor text corresponding to the link. withParentUrl(parentUrl) parentUrl is a string representing the parent (source page) URL. This function returns syntheticsLinkObject withStatusCode(statusCode) statusCode is a string representing the status code. This function returns syntheticsLinkObject withFailureReason(failureReason) failureReason is a string representing the failure reason. This function returns syntheticsLinkObject addScreenshotResult(screenshotResult) screenshotResult is an object. It is an instance of ScreenshotResult that was returned by the Synthetics function takeScreenshot. The object includes the following: • fileName— A string representing the screenshotFileName • pageUrl (optional) • error (optional) Node.js library classes and functions that apply to API canaries only The following CloudWatch Synthetics library functions for Node.js are useful only for API canaries. Topics • executeHttpStep(stepName, requestOptions, [callback], [stepConfig]) executeHttpStep(stepName, requestOptions, [callback], [stepConfig]) Executes the provided HTTP request as a step, and publishes SuccessPercent (pass/fail) and Duration metrics. executeHttpStep uses either HTTP or HTTPS native functions under the hood, depending upon the protocol specified in the request. Creating a canary 1743 Amazon CloudWatch User Guide This function also adds a step execution summary to the canary's report. The summary includes details about each HTTP request, such as the following: • Start time • End time • Status (PASSED/FAILED) • Failure reason, if it failed • HTTP call details such as request/response headers, body, status code, status message, and performance timings. Topics • Parameters • Examples of using executeHttpStep Parameters stepName(String) Specifies the name of the step. This name is also used for publishing CloudWatch metrics for this step. requestOptions(Object or String) The value of this parameter can be a URL, a URL string, or an object. If it is an object, then it must be a set of configurable options to make an HTTP request. It supports all options in http.request(options[, callback]) in the Node.js documentation. In addition to these Node.js options, requestOptions supports the additional parameter body. You can use the body parameter to pass data as a request body. callback(response) (Optional) This is a user function which is invoked with the HTTP response. The response is of the type Class: http.IncomingMessage. stepConfig(object) (Optional) Use this parameter to override global synthetics configurations with a different configuration for this step. Creating a canary 1744 Amazon CloudWatch User Guide Examples of using executeHttpStep The following series of examples build on each other to illustrate the various uses of this option. This first example configures request parameters. You can pass a URL as requestOptions: let requestOptions = 'https://www.amazon.com'; Or you can pass a set of options: let requestOptions = { 'hostname': 'myproductsEndpoint.com',
acw-ug-468
acw-ug.pdf
468
body. callback(response) (Optional) This is a user function which is invoked with the HTTP response. The response is of the type Class: http.IncomingMessage. stepConfig(object) (Optional) Use this parameter to override global synthetics configurations with a different configuration for this step. Creating a canary 1744 Amazon CloudWatch User Guide Examples of using executeHttpStep The following series of examples build on each other to illustrate the various uses of this option. This first example configures request parameters. You can pass a URL as requestOptions: let requestOptions = 'https://www.amazon.com'; Or you can pass a set of options: let requestOptions = { 'hostname': 'myproductsEndpoint.com', 'method': 'GET', 'path': '/test/product/validProductName', 'port': 443, 'protocol': 'https:' }; The next example creates a callback function which accepts a response. By default, if you do not specify callback, CloudWatch Synthetics validates that the status is between 200 and 299 inclusive. // Handle validation for positive scenario const callback = async function(res) { return new Promise((resolve, reject) => { if (res.statusCode < 200 || res.statusCode > 299) { throw res.statusCode + ' ' + res.statusMessage; } let responseBody = ''; res.on('data', (d) => { responseBody += d; }); res.on('end', () => { // Add validation on 'responseBody' here if required. For ex, your status code is 200 but data might be empty resolve(); }); }); }; Creating a canary 1745 Amazon CloudWatch User Guide The next example creates a configuration for this step that overrides the global CloudWatch Synthetics configuration. The step configuration in this example allows request headers, response headers, request body (post data), and response body in your report and restrict 'X-Amz-Security- Token' and 'Authorization' header values. By default, these values are not included in the report for security reasons. If you choose to include them, the data is only stored in your S3 bucket. // By default headers, post data, and response body are not included in the report for security reasons. // Change the configuration at global level or add as step configuration for individual steps let stepConfig = { includeRequestHeaders: true, includeResponseHeaders: true, restrictedHeaders: ['X-Amz-Security-Token', 'Authorization'], // Restricted header values do not appear in report generated. includeRequestBody: true, includeResponseBody: true }; This final example passes your request to executeHttpStep and names the step. await synthetics.executeHttpStep('Verify GET products API', requestOptions, callback, stepConfig); With this set of examples, CloudWatch Synthetics adds the details from each step in your report and produces metrics for each step using stepName. You will see successPercent and duration metrics for the Verify GET products API step. You can monitor your API performance by monitoring the metrics for your API call steps. For a sample complete script that uses these functions, see Multi-step API canary. Library functions available for Python canary scripts using Selenium This section lists the Selenium library functions available for Python canary scripts. Topics • Python and Selenium library classes and functions that apply to all canaries • Python and Selenium library classes and functions that apply to UI canaries only Creating a canary 1746 Amazon CloudWatch User Guide Python and Selenium library classes and functions that apply to all canaries The following CloudWatch Synthetics Selenium library functions for Python are useful for all canaries. Topics • SyntheticsConfiguration class • SyntheticsLogger class SyntheticsConfiguration class You can use the SyntheticsConfiguration class to configure the behavior of Synthetics library functions. For example, you can use this class to configure the executeStep() function to not capture screenshots. You can set CloudWatch Synthetics configurations at the global level. Function definitions: set_config(options) from aws_synthetics.common import synthetics_configuration options is an object, which is a set of configurable options for your canary. The following sections explain the possible fields in options. • screenshot_on_step_start (boolean)— Whether to take a screenshot before starting a step. • screenshot_on_step_success (boolean)— Whether to take a screenshot after completing a successful step. • screenshot_on_step_failure (boolean)— Whether to take a screenshot after a step fails. with_screenshot_on_step_start(screenshot_on_step_start) Accepts a Boolean argument, which indicates whether to take a screenshot before starting a step. with_screenshot_on_step_success(screenshot_on_step_success) Accepts a Boolean argument, which indicates whether to take a screenshot after completing a step successfully. Creating a canary 1747 Amazon CloudWatch User Guide with_screenshot_on_step_failure(screenshot_on_step_failure) Accepts a Boolean argument, which indicates whether to take a screenshot after a step fails. get_screenshot_on_step_start() Returns whether to take a screenshot before starting a step. get_screenshot_on_step_success() Returns whether to take a screenshot after completing a step successfully. get_screenshot_on_step_failure() Returns whether to take a screenshot after a step fails. disable_step_screenshots() Disables all screenshot options (get_screenshot_on_step_start, get_screenshot_on_step_success, and get_screenshot_on_step_failure). enable_step_screenshots() Enables all screenshot options (get_screenshot_on_step_start, get_screenshot_on_step_success, and get_screenshot_on_step_failure). By default, all these methods are enabled. setConfig(options) regarding CloudWatch metrics For canaries using syn-python-selenium-1.1 or later, the (options) for setConfig can include the following Boolean parameters that determine which metrics are published by the canary. The default for each of these options is true. The options that start with aggregated
acw-ug-469
acw-ug.pdf
469
to take a screenshot before starting a step. get_screenshot_on_step_success() Returns whether to take a screenshot after completing a step successfully. get_screenshot_on_step_failure() Returns whether to take a screenshot after a step fails. disable_step_screenshots() Disables all screenshot options (get_screenshot_on_step_start, get_screenshot_on_step_success, and get_screenshot_on_step_failure). enable_step_screenshots() Enables all screenshot options (get_screenshot_on_step_start, get_screenshot_on_step_success, and get_screenshot_on_step_failure). By default, all these methods are enabled. setConfig(options) regarding CloudWatch metrics For canaries using syn-python-selenium-1.1 or later, the (options) for setConfig can include the following Boolean parameters that determine which metrics are published by the canary. The default for each of these options is true. The options that start with aggregated determine whether the metric is emitted without the CanaryName dimension. You can use these metrics to see the aggregated results for all of your canaries. The other options determine whether the metric is emitted with the CanaryName dimension. You can use these metrics to see results for each individual canary. For a list of CloudWatch metrics emitted by canaries, see CloudWatch metrics published by canaries. • failed_canary_metric (boolean)— Whether to emit the Failed metric (with the CanaryName dimension) for this canary. The default is true. • failed_requests_metric (boolean)— Whether to emit the Failed requests metric (with the CanaryName dimension) for this canary. The default is true. Creating a canary 1748 Amazon CloudWatch User Guide • 2xx_metric (boolean)— Whether to emit the 2xx metric (with the CanaryName dimension) for this canary. The default is true. • 4xx_metric (boolean)— Whether to emit the 4xx metric (with the CanaryName dimension) for this canary. The default is true. • 5xx_metric (boolean)— Whether to emit the 5xx metric (with the CanaryName dimension) for this canary. The default is true. • step_duration_metric (boolean)— Whether to emit the Step duration metric (with the CanaryName StepName dimensions) for this canary. The default is true. • step_success_metric (boolean)— Whether to emit the Step success metric (with the CanaryName StepName dimensions) for this canary. The default is true. • aggregated_failed_canary_metric (boolean)— Whether to emit the Failed metric (without the CanaryName dimension) for this canary. The default is true. • aggregated_failed_requests_metric (boolean)— Whether to emit the Failed Requests metric (without the CanaryName dimension) for this canary. The default is true. • aggregated_2xx_metric (boolean)— Whether to emit the 2xx metric (without the CanaryName dimension) for this canary. The default is true. • aggregated_4xx_metric (boolean)— Whether to emit the 4xx metric (without the CanaryName dimension) for this canary. The default is true. • aggregated_5xx_metric (boolean)— Whether to emit the 5xx metric (without the CanaryName dimension) for this canary. The default is true. with_2xx_metric(2xx_metric) Accepts a Boolean argument, which specifies whether to emit a 2xx metric with the CanaryName dimension for this canary. with_4xx_metric(4xx_metric) Accepts a Boolean argument, which specifies whether to emit a 4xx metric with the CanaryName dimension for this canary. with_5xx_metric(5xx_metric) Accepts a Boolean argument, which specifies whether to emit a 5xx metric with the CanaryName dimension for this canary. withAggregated2xxMetric(aggregated2xxMetric) Creating a canary 1749 Amazon CloudWatch User Guide Accepts a Boolean argument, which specifies whether to emit a 2xx metric with no dimension for this canary. withAggregated4xxMetric(aggregated4xxMetric) Accepts a Boolean argument, which specifies whether to emit a 4xx metric with no dimension for this canary. with_aggregated_5xx_metric(aggregated_5xx_metric) Accepts a Boolean argument, which specifies whether to emit a 5xx metric with no dimension for this canary. with_aggregated_failed_canary_metric(aggregated_failed_canary_metric) Accepts a Boolean argument, which specifies whether to emit a Failed metric with no dimension for this canary. with_aggregated_failed_requests_metric(aggregated_failed_requests_metric) Accepts a Boolean argument, which specifies whether to emit a Failed requests metric with no dimension for this canary. with_failed_canary_metric(failed_canary_metric) Accepts a Boolean argument, which specifies whether to emit a Failed metric with the CanaryName dimension for this canary. with_failed_requests_metric(failed_requests_metric) Accepts a Boolean argument, which specifies whether to emit a Failed requests metric with the CanaryName dimension for this canary. with_step_duration_metric(step_duration_metric) Accepts a Boolean argument, which specifies whether to emit a Duration metric with the CanaryName dimension for this canary. with_step_success_metric(step_success_metric) Accepts a Boolean argument, which specifies whether to emit a StepSuccess metric with the CanaryName dimension for this canary. Creating a canary 1750 Amazon CloudWatch User Guide Methods to enable or disable metrics disable_aggregated_request_metrics() Disables the canary from emitting all request metrics that are emitted with no CanaryName dimension. disable_request_metrics() Disables all request metrics, including both per-canary metrics and metrics aggregated across all canaries. disable_step_metrics() Disables all step metrics, including both step success metrics and step duration metrics. enable_aggregated_request_metrics() Enables the canary to emit all request metrics that are emitted with no CanaryName dimension. enable_request_metrics() Enables all request metrics, including both per-canary metrics and metrics aggregated across all canaries. enable_step_metrics() Enables all step metrics, including both step success metrics and step duration metrics. Usage in UI canaries First, import the synthetics dependency and fetch the configuration. Then, set the configuration for each option by calling the setConfig method using one of the following options. from
acw-ug-470
acw-ug.pdf
470
both per-canary metrics and metrics aggregated across all canaries. disable_step_metrics() Disables all step metrics, including both step success metrics and step duration metrics. enable_aggregated_request_metrics() Enables the canary to emit all request metrics that are emitted with no CanaryName dimension. enable_request_metrics() Enables all request metrics, including both per-canary metrics and metrics aggregated across all canaries. enable_step_metrics() Enables all step metrics, including both step success metrics and step duration metrics. Usage in UI canaries First, import the synthetics dependency and fetch the configuration. Then, set the configuration for each option by calling the setConfig method using one of the following options. from aws_synthetics.common import synthetics_configuration synthetics_configuration.set_config( { "screenshot_on_step_start": False, "screenshot_on_step_success": False, "screenshot_on_step_failure": True } ) Creating a canary 1751 Amazon CloudWatch or Or User Guide synthetics_configuration.with_screenshot_on_step_start(False).with_screenshot_on_step_success(False).with_screenshot_on_step_failure(True) To disable all screenshots, use the disableStepScreenshots() function as in this example. synthetics_configuration.disable_step_screenshots() You can enable and disable screenshots at any point in the code. For example, to disable screenshots only for one step, disable them before running that step and then enable them after the step. set_config(options) for UI canaries Starting with syn-python-selenium-1.1, for UI canaries, set_config can include the following Boolean parameters: • continue_on_step_failure (boolean)— Whether to continue with running the canary script after a step fails (this refers to the executeStep function). If any steps fail, the canary run will still be marked as failed. The default is false. SyntheticsLogger class synthetics_logger writes logs out to both the console and to a local log file at the same log level. This log file is written to both locations only if the log level is at or below the desired logging level of the log function that was called. The logging statements in the local log file are prepended with "DEBUG: ", "INFO: ", and so on to match the log level of the function that was called. Using synthetics_logger is not required to create a log file that is uploaded to your Amazon S3 results location. You could instead create a different log file in the /tmp folder. Any files created under the /tmp folder are uploaded to the results location in the S3 bucket as artifacts. To use synthetics_logger: from aws_synthetics.common import synthetics_logger Creating a canary 1752 Amazon CloudWatch Useful function definitions: Get log level: log_level = synthetics_logger.get_level() Set log level: synthetics_logger.set_level() User Guide Log a message with a specified level. The level can be DEBUG, INFO, WARN, or ERROR, as in the following syntax examples: synthetics_logger.debug(message, *args, **kwargs) synthetics_logger.info(message, *args, **kwargs) synthetics_logger.log(message, *args, **kwargs) synthetics_logger.warn(message, *args, **kwargs) synthetics_logger.error(message, *args, **kwargs) For information about debug parameters, see the standard Python documentation at logging.debug In these logging functions, the message is the message format string. The args are the arguments that are merged into msg using the string formatting operator. There are three keyword arguments in kwargs: • exc_info– If not evaluated as false, adds exception information to the logging message. • stack_info– defaults to false. If true, adds stack information to the logging message, including the actual logging call. • extra– The third optional keyword argument, which you can use to pass in a dictionary that is used to populate the __dict__ of the LogRecord created for the logging event with user- defined attributes. Creating a canary 1753 Amazon CloudWatch Examples: Log a message with the level DEBUG: User Guide synthetics_logger.debug('Starting step - login.') Log a message with the level INFO. logger.log is a synonym for logger.info: synthetics_logger.info('Successfully completed step - login.') or synthetics_logger.log('Successfully completed step - login.') Log a message with the level WARN: synthetics_logger.warn('Warning encountered trying to publish %s', 'CloudWatch Metric') Log a message with the level ERROR: synthetics_logger.error('Error encountered trying to publish %s', 'CloudWatch Metric') Log an exception: synthetics_logger.exception(message, *args, **kwargs) Logs a message with level ERROR. Exception information is added to the logging message. You should call this function only from an exception handler. For information about exception parameters, see the standard Python documentation at logging.exception The message is the message format string. The args are the arguments, which are merged into msg using the string formatting operator. There are three keyword arguments in kwargs: • exc_info– If not evaluated as false, adds exception information to the logging message. • stack_info– defaults to false. If true, adds stack information to the logging message, including the actual logging call. Creating a canary 1754 Amazon CloudWatch User Guide • extra– The third optional keyword argument, which you can use to pass in a dictionary that is used to populate the __dict__ of the LogRecord created for the logging event with user- defined attributes. Example: synthetics_logger.exception('Error encountered trying to publish %s', 'CloudWatch Metric') Python and Selenium library classes and functions that apply to UI canaries only The following CloudWatch Synthetics Selenium library functions for Python are useful only for UI canaries. Topics • SyntheticsBrowser class • SyntheticsWebDriver class SyntheticsBrowser class When