

# Amazon SNS message delivery status
<a name="sns-topic-attributes"></a>

Amazon SNS provides support for logging the delivery status of notification messages sent to topics with the following Amazon SNS endpoints: 
+ Amazon Data Firehose
+ Amazon Simple Queue Service
+ Amazon Lambda
+ HTTPS
+ Platform application endpoint

Delivery status logs are sent to Amazon CloudWatch Logs, providing insights into message delivery operations. These logs help you:
+ Determine whether a message was successfully delivered to an endpoint.
+ Identify the response from the endpoint to Amazon SNS.
+ Measure message dwell time (time between publish timestamp and handoff to the endpoint).

You can configure delivery status logging using the Amazon Web Services Management Console, Amazon SDKs, Query API, or Amazon CloudFormation.

# Prerequisites for delivery status logging
<a name="topics-attrib-prereq"></a>

This topic outlines the necessary IAM permissions for enabling Amazon SNS to write delivery logs to CloudWatch and explains the default log group naming convention. This ensures you have the correct setup and access to monitor and analyze message delivery logs in CloudWatch logs.

**Required IAM permissions**

The IAM role attached for delivery status logging must include the following permissions to enable Amazon SNS to write to CloudWatch Logs. You can use an existing role with these permissions or create a new role during setup.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws-cn:logs:*:*:*"
    }
  ]
}
```

------

**Log group naming convention**

By default, Amazon SNS creates CloudWatch log groups for delivery status logs using the following naming convention. Log streams within this group correspond to the endpoint protocols (for example, Lambda, Amazon SQS). Ensure you have permissions to view these logs in the CloudWatch Logs console.

```
sns/<region>/<account-id>/<topic-name>
```

# Configuring delivery status logging using the Amazon Web Services Management Console
<a name="topics-attrib"></a>

This topic explains how to enable message delivery status logging for Amazon SNS topics, including configuring logging settings, assigning IAM roles, and verifying that CloudWatch Logs capture delivery logs for monitoring and troubleshooting.

1. Sign in to the [Amazon SNS console](https://console.amazonaws.cn/sns/home).

1. On the navigation panel, choose **Topics**.

1. Select the desired **topic** and then choose **Edit**.

1. Expand the **Delivery status logging** section.

1. Choose the **protocol** for which you want to enable logging (for example, HTTP, Lambda, Amazon SQS).

1. Enter the **Success sample rate**, which is the percentage of successful messages for which you want to receive CloudWatch Logs.

1. In the **IAM roles** section, you must configure roles for both **success** and **failure** logging:
   + **Use an existing service role** – Select an existing IAM role that has the required permissions for Amazon SNS to write logs to CloudWatch.
   + **Create a new service role** – Choose **Create new roles** to define the IAM roles for successful and failed deliveries in the IAM console. For permission details, see [Prerequisites for delivery status logging](topics-attrib-prereq.md).

1. Choose **Save changes**.

   After enabling logging, you can view and parse the CloudWatch Logs containing the message delivery status. For more information about using CloudWatch, see the [CloudWatch documentation](http://www.amazonaws.cn/documentation/cloudwatch).

**Verifying log setup**

1. Sign into the CloudWatch Logs console.

1. Locate the log group named `sns/<region>/<account-id>/<topic-name>`.

1. Ensure log streams exist for the configured endpoint protocol.

1. Send a test message to your topic and confirm that log entries appear, indicating successful or failed deliveries.

# Configuring delivery status logging using the Amazon SDKs
<a name="msg-status-sdk"></a>

The Amazon SDKs provide APIs in several languages to set topic attributes for message delivery status logging. For example, use the [SetTopicAttributes](https://docs.amazonaws.cn/sns/latest/api/API_SetTopicAttributes.html) API to configure:
+ `LambdaSuccessFeedbackRoleArn` – IAM role for successful message delivery to Lambda endpoints.
+ `LambdaSuccessFeedbackSampleRate` – Sampling rate for successful messages to Lambda endpoints.
+ `LambdaFailureFeedbackRoleArn` – IAM role for failed message delivery to Lambda endpoints.

**Example Amazon CLI command**

```
aws sns set-topic-attributes \
    --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --attribute-name LambdaSuccessFeedbackRoleArn \
    --attribute-value arn:aws:iam::123456789012:role/MyFeedbackRole
```

## Topic attributes
<a name="topic-attributes"></a>

Use the following topic attribute name values for message delivery status:

**HTTP**
+ `HTTPSuccessFeedbackRoleArn` – Successful message delivery status for an Amazon SNS topic that is subscribed to an HTTP endpoint. 
+ `HTTPSuccessFeedbackSampleRate` – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an HTTP endpoint.
+ `HTTPFailureFeedbackRoleArn` – Failed message delivery status for an Amazon SNS topic that is subscribed to an HTTP endpoint.

**Amazon Data Firehose**
+ `FirehoseSuccessFeedbackRoleArn` – Successful message delivery status for an Amazon SNS topic that is subscribed to an Amazon Data Firehose endpoint.
+ `FirehoseSuccessFeedbackSampleRate` – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon Data Firehose endpoint.
+ `FirehoseFailureFeedbackRoleArn` – Failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon Data Firehose endpoint. 

**Amazon Lambda**
+ `LambdaSuccessFeedbackRoleArn` – Successful message delivery status for an Amazon SNS topic that is subscribed to an Lambda endpoint.
+ `LambdaSuccessFeedbackSampleRate` – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Lambda endpoint.
+ `LambdaFailureFeedbackRoleArn` – Failed message delivery status for an Amazon SNS topic that is subscribed to an Lambda endpoint. 

**Platform application endpoints**
+ `ApplicationSuccessFeedbackRoleArn` – Successful message delivery status for an Amazon SNS topic that is subscribed to an Amazon application endpoint.
+ `ApplicationSuccessFeedbackSampleRate` – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon application endpoint.
+ `ApplicationFailureFeedbackRoleArn` – Failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon application endpoint.
**Note**  
Additionally, you can configure application attributes to log delivery status directly to push notification services. For more information, see [Using Amazon SNS Application Attributes for Message Delivery Status](https://docs.amazonaws.cn/sns/latest/dg/sns-msg-status.html). 

**Amazon SQS**
+ `SQSSuccessFeedbackRoleArn` – Successful message delivery status for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint. 
+ `SQSSuccessFeedbackSampleRate` – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint. 
+ `SQSFailureFeedbackRoleArn` – Failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint. 

Logs for platform application endpoints are written to the same CloudWatch Logs group as other endpoints.

**Note**  
 The `<ENDPOINT>SuccessFeedbackRoleArn` and `<ENDPOINT>FailureFeedbackRoleArn` attributes are used to give Amazon SNS write access to use CloudWatch Logs on your behalf. The `<ENDPOINT>SuccessFeedbackSampleRate` attribute is for specifying the sample rate percentage (0-100) of successfully delivered messages. After you configure the `<ENDPOINT>FailureFeedbackRoleArn` attribute, then all failed message deliveries generate CloudWatch Logs. 

# Amazon SDK examples to configure topic attributes
<a name="topic-attributes-sdks"></a>

The following code examples show how to use `SetTopicAttributes`.

------
#### [ CLI ]

**Amazon CLI**  
**To set an attribute for a topic**  
The following `set-topic-attributes` example sets the `DisplayName` attribute for the specified topic.  

```
aws sns set-topic-attributes \
    --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --attribute-name DisplayName \
    --attribute-value MyTopicDisplayName
```
This command produces no output.  
+  For API details, see [SetTopicAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-topic-attributes.html) in *Amazon CLI Command Reference*. 

------
#### [ Java ]

**SDK for Java 2.x**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples). 

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest;
import software.amazon.awssdk.services.sns.model.SetTopicAttributesResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SetTopicAttributes {

    public static void main(String[] args) {
        final String usage = """

                Usage:    <attribute> <topicArn> <value>

                Where:
                   attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy .
                   topicArn - The ARN of the topic.\s
                   value - The value for the attribute.
                """;

        if (args.length < 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String attribute = args[0];
        String topicArn = args[1];
        String value = args[2];

        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        setTopAttr(snsClient, attribute, topicArn, value);
        snsClient.close();
    }

    public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) {
        try {
            SetTopicAttributesRequest request = SetTopicAttributesRequest.builder()
                    .attributeName(attribute)
                    .attributeValue(value)
                    .topicArn(topicArn)
                    .build();

            SetTopicAttributesResponse result = snsClient.setTopicAttributes(request);
            System.out.println(
                    "\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.topicArn()
                            + " updated " + request.attributeName() + " to " + request.attributeValue());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  For API details, see [SetTopicAttributes](https://docs.amazonaws.cn/goto/SdkForJavaV2/sns-2010-03-31/SetTopicAttributes) in *Amazon SDK for Java 2.x API Reference*. 

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples). 
Create the client in a separate module and export it.  

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```
Import the SDK and client modules and call the API.  

```
import { SetTopicAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const setTopicAttributes = async (
  topicArn = "TOPIC_ARN",
  attributeName = "DisplayName",
  attributeValue = "Test Topic",
) => {
  const response = await snsClient.send(
    new SetTopicAttributesCommand({
      AttributeName: attributeName,
      AttributeValue: attributeValue,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```
+  For more information, see [Amazon SDK for JavaScript Developer Guide](https://docs.amazonaws.cn/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topicsstttopicattributes). 
+  For API details, see [SetTopicAttributes](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/sns/command/SetTopicAttributesCommand) in *Amazon SDK for JavaScript API Reference*. 

------
#### [ Kotlin ]

**SDK for Kotlin**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples). 

```
suspend fun setTopAttr(
    attribute: String?,
    topicArnVal: String?,
    value: String?,
) {
    val request =
        SetTopicAttributesRequest {
            attributeName = attribute
            attributeValue = value
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.setTopicAttributes(request)
        println("Topic ${request.topicArn} was updated.")
    }
}
```
+  For API details, see [SetTopicAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html) in *Amazon SDK for Kotlin API reference*. 

------
#### [ PHP ]

**SDK for PHP**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples). 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Configure the message delivery status attributes for an Amazon SNS Topic.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);
$attribute = 'Policy | DisplayName | DeliveryPolicy';
$value = 'First Topic';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->setTopicAttributes([
        'AttributeName' => $attribute,
        'AttributeValue' => $value,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  For API details, see [SetTopicAttributes](https://docs.amazonaws.cn/goto/SdkForPHPV3/sns-2010-03-31/SetTopicAttributes) in *Amazon SDK for PHP API Reference*. 

------
#### [ Ruby ]

**SDK for Ruby**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples). 

```
# Service class to enable an SNS resource with a specified policy
class SnsResourceEnabler
  # Initializes the SnsResourceEnabler with an SNS resource client
  #
  # @param sns_resource [Aws::SNS::Resource] The SNS resource client
  def initialize(sns_resource)
    @sns_resource = sns_resource
    @logger = Logger.new($stdout)
  end

  # Sets a policy on a specified SNS topic
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param resource_arn [String] The ARN of the resource to include in the policy
  # @param policy_name [String] The name of the policy attribute to set
  def enable_resource(topic_arn, resource_arn, policy_name)
    policy = generate_policy(topic_arn, resource_arn)
    topic = @sns_resource.topic(topic_arn)

    topic.set_attributes({
                           attribute_name: policy_name,
                           attribute_value: policy
                         })
    @logger.info("Policy #{policy_name} set successfully for topic #{topic_arn}.")
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Failed to set policy: #{e.message}")
  end

  private

  # Generates a policy string with dynamic resource ARNs
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param resource_arn [String] The ARN of the resource
  # @return [String] The policy as a JSON string
  def generate_policy(topic_arn, resource_arn)
    {
      Version: '2008-10-17',
      Id: '__default_policy_ID',
      Statement: [{
        Sid: '__default_statement_ID',
        Effect: 'Allow',
        Principal: { "AWS": '*' },
        Action: ['SNS:Publish'],
        Resource: topic_arn,
        Condition: {
          ArnEquals: {
            "AWS:SourceArn": resource_arn
          }
        }
      }]
    }.to_json
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_arn = 'MY_TOPIC_ARN' # Should be replaced with a real topic ARN
  resource_arn = 'MY_RESOURCE_ARN' # Should be replaced with a real resource ARN
  policy_name = 'POLICY_NAME' # Typically, this is "Policy"

  sns_resource = Aws::SNS::Resource.new
  enabler = SnsResourceEnabler.new(sns_resource)

  enabler.enable_resource(topic_arn, resource_arn, policy_name)
end
```
+  For more information, see [Amazon SDK for Ruby Developer Guide](https://docs.amazonaws.cn/sdk-for-ruby/v3/developer-guide/sns-example-enable-resource.html). 
+  For API details, see [SetTopicAttributes](https://docs.amazonaws.cn/goto/SdkForRubyV3/sns-2010-03-31/SetTopicAttributes) in *Amazon SDK for Ruby API Reference*. 

------
#### [ SAP ABAP ]

**SDK for SAP ABAP**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples). 

```
    TRY.
        lo_sns->settopicattributes(
            iv_topicarn = iv_topic_arn
            iv_attributename  = iv_attribute_name
            iv_attributevalue = iv_attribute_value ).
        MESSAGE 'Set/updated SNS topic attributes.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  For API details, see [SetTopicAttributes](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html) in *Amazon SDK for SAP ABAP API reference*. 

------

# Configuring delivery status logging using Amazon CloudFormation
<a name="msg-status-cloudformation"></a>

To configure `DeliveryStatusLogging` using Amazon CloudFormation, use a JSON or YAML template to create an Amazon CloudFormation stack. For more information, see the `DeliveryStatusLogging` property of the `AWS::SNS::Topic` resource in the Amazon CloudFormation User Guide. Below are examples of Amazon CloudFormation templates in JSON and YAML to create a new topic or update an existing topic with all `DeliveryStatusLogging` attributes for the Amazon SQS protocol.

Ensure the IAM roles referenced in `SuccessFeedbackRoleArn` and `FailureFeedbackRoleArn` have the required CloudWatch Logs permissions.

------
#### [ JSON ]

```
"Resources": {
    "MySNSTopic" : {
        "Type" : "AWS::SNS::Topic",
        "Properties" : {
            "TopicName" : "TestTopic",
            "DisplayName" : "TEST",
            "SignatureVersion" : "2",
            "DeliveryStatusLogging" : [{
                "Protocol": "sqs",
                "SuccessFeedbackSampleRate": "45",
                "SuccessFeedbackRoleArn": "arn:aws-cn:iam::123456789012:role/SNSSuccessFeedback_test1",
                "FailureFeedbackRoleArn": "arn:aws-cn:iam::123456789012:role/SNSFailureFeedback_test2"
            }]
        }
    }
}
```

------
#### [ YAML ]

```
Resources:
  MySNSTopic:
    Type: AWS::SNS::Topic
    Properties:
      TopicName:TestTopic
      DisplayName:TEST
      SignatureVersion:2
      DeliveryStatusLogging:
       - Protocol: sqs
         SuccessFeedbackSampleRate: 45
         SuccessFeedbackRoleArn: arn:aws-cn:iam::123456789012:role/SNSSuccessFeedback_test1
         FailureFeedbackRoleArn: arn:aws-cn:iam::123456789012:role/SNSFailureFeedback_test2
```

------