

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

# Amazon SNS 消息传输状态
<a name="sns-topic-attributes"></a>

对于使用下列 Amazon SNS 端点的主题，Amazon SNS 支持记录发送到这些主题的通知消息的传输状态：
+ Amazon Data Firehose
+ Amazon Simple Queue Service
+ AWS Lambda
+ HTTPS
+ 平台应用程序终端节点

发送状态日志将发送到 Amazon CloudWatch Logs，从而提供对消息传输操作的见解。这些日志可以帮助您：
+ 确定消息是否已成功传输到端点。
+ 识别从端点发送到 Amazon SNS 的响应。
+ 衡量消息停留时间（从发布时间戳到移交给端点之间的时间）。

您可以使用 AWS 管理控制台、 AWS SDKs、查询 API 或配置传送状态日志记录 AWS CloudFormation。

# 配置传输状态日志记录的先决条件
<a name="topics-attrib-prereq"></a>

本主题概述了允许 Amazon SNS 向其写入传输日志所必需的 IAM 权限， CloudWatch 并解释了默认日志组命名约定。这可确保您拥有正确的设置和访问权限，以监控和分析日志中的消息传送 CloudWatch 日志。

**所需的 IAM 权限**

为记录交付状态而附加的 IAM 角色必须包含以下权限，才能让 Amazon SNS 写入 CloudWatch 日志。您可以在设置过程中使用具有这些权限的现有角色，也可以创建新角色。

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

****  

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

------

**日志组命名约定**

默认情况下，Amazon SNS 使用以下命名约定为传输状态 CloudWatch 日志创建日志组。该组中的日志流对应于端点协议（例如 Lambda、Amazon SQS）。确保您有权在日志控制台中查看这些 CloudWatch 日志。

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

# 使用配置传送状态日志 AWS 管理控制台
<a name="topics-attrib"></a>

本主题介绍如何为 Amazon SNS 主题启用消息传输状态日志，包括配置日志设置、分配 IAM 角色以及验证日志是否捕获传输 CloudWatch 日志以进行监控和故障排除。

1. 登录 [Amazon SNS 控制台](https://console.aws.amazon.com/sns/home)。

1. 在导航面板上，选择**主题**。

1. 选择所需的**主题**，然后选择**编辑**。

1. 展开**传输状态日志记录**部分。

1. 选择要为其启用日志记录功能的**协议**（例如 HTTP、Lambda、Amazon SQS）。

1. 输入**成功采样率**，即您希望接收 CloudWatch 日志的成功消息的百分比。

1. 在 **IAM 角色**部分，您必须为**成功**和**失败**日志记录配置角色：
   + **使用现有服务角色**-选择具有 Amazon SNS 写入日志所需权限的现有 IAM 角色。 CloudWatch
   + **创建新的服务角色** – 选择**创建新角色**，以便在 IAM 控制台中为成功和失败的传输定义 IAM 角色。有关权限的详细信息，请参阅[配置传输状态日志记录的先决条件](topics-attrib-prereq.md)。

1. 选择**保存更改**。

   启用日志记录后，您可以查看和解析包含消息传送状态的 CloudWatch 日志。有关使用的更多信息 CloudWatch，请参阅[CloudWatch文档](https://aws.amazon.com/documentation/cloudwatch)。

**验证日志设置**

1. 登录 CloudWatch 日志控制台。

1. 找到名为 `sns/<region>/<account-id>/<topic-name>` 的日志组。

1. 确保已配置的端点协议存在日志流。

1. 向主题发送测试消息，并确认日志条目是否出现，该日志条目会表明传输成功还是失败。

# 使用配置传送状态日志 AWS SDKs
<a name="msg-status-sdk"></a>

 AWS SDKs 提供了多种 APIs 语言来设置消息传送状态记录的主题属性。例如，使用 [SetTopicAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetTopicAttributes.html)API 来配置：
+ `LambdaSuccessFeedbackRoleArn` – 向 Lambda 端点传输成功消息的 IAM 角色。
+ `LambdaSuccessFeedbackSampleRate` – 传输到 Lambda 端点的成功消息采样率。
+ `LambdaFailureFeedbackRoleArn` – 向 Lambda 端点传输失败消息的 IAM 角色。

** AWS CLI 命令示例**

```
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
```

## 主题属性
<a name="topic-attributes"></a>

对消息传输状态使用下列主题属性名称值：

**HTTP**
+ `HTTPSuccessFeedbackRoleArn` – 订阅到 HTTP 端点的 Amazon SNS 主题的成功消息传输状态。
+ `HTTPSuccessFeedbackSampleRate` – 订阅到 HTTP 端点的 Amazon SNS 主题的成功消息采样百分比。
+ `HTTPFailureFeedbackRoleArn` – 订阅到 HTTP 端点的 Amazon SNS 主题的失败消息传输状态。

**Amazon Data Firehose**
+ `FirehoseSuccessFeedbackRoleArn` – 订阅到 Amazon Data Firehose 端点的 Amazon SNS 主题的成功消息传输状态。
+ `FirehoseSuccessFeedbackSampleRate` – 订阅到 Amazon Data Firehose 端点的 Amazon SNS 主题的成功消息采样百分比。
+ `FirehoseFailureFeedbackRoleArn` – 订阅到 Amazon Data Firehose 端点的 Amazon SNS 主题的失败消息传输状态。

**AWS Lambda**
+ `LambdaSuccessFeedbackRoleArn` – 订阅到 Lambda 端点的 Amazon SNS 主题的成功消息传输状态。
+ `LambdaSuccessFeedbackSampleRate` – 订阅到 Lambda 端点的 Amazon SNS 主题的成功消息采样百分比。
+ `LambdaFailureFeedbackRoleArn` – 订阅到 Lambda 端点的 Amazon SNS 主题的失败消息传输状态。

**平台应用程序端点**
+ `ApplicationSuccessFeedbackRoleArn`— 订阅应用程序终端节点的 Amazon SNS 主题的成功消息传输状态。 AWS 
+ `ApplicationSuccessFeedbackSampleRate` – 订阅到 AWS 应用程序端点的 Amazon SNS 主题的成功消息采样百分比。
+ `ApplicationFailureFeedbackRoleArn`— 订阅应用程序终端节点的 Amazon SNS 主题的消息传输失败状态。 AWS 
**注意**  
此外，您还可以配置应用程序属性，直接将传输状态记录到推送通知服务中。有关更多信息，请参阅[使用用于消息传输状态的 Amazon SNS 应用程序属性](https://docs.aws.amazon.com/sns/latest/dg/sns-msg-status.html)。

**Amazon SQS**
+ `SQSSuccessFeedbackRoleArn` – 订阅到 Amazon SQS 端点的 Amazon SNS 主题的成功消息传输状态。
+ `SQSSuccessFeedbackSampleRate` – 订阅到 Amazon SQS 端点的 Amazon SNS 主题的成功消息采样百分比。
+ `SQSFailureFeedbackRoleArn` – 订阅到 Amazon SQS 端点的 Amazon SNS 主题的失败消息传输状态。

平台应用程序终端节点的日志与其他终端节点一样写入同一个 CloudWatch 日志组。

**注意**  
 `<ENDPOINT>SuccessFeedbackRoleArn`和`<ENDPOINT>FailureFeedbackRoleArn`属性用于向 Amazon SNS 授予代表您使用 CloudWatch 日志的写入权限。`<ENDPOINT>SuccessFeedbackSampleRate` 属性用于指定成功传输消息的采样率百分比 (0-100)。配置该`<ENDPOINT>FailureFeedbackRoleArn`属性后，所有失败的消息传送都会生成 CloudWatch 日志。

# AWS 用于配置主题属性的 SDK 示例
<a name="topic-attributes-sdks"></a>

以下代码示例演示如何使用 `SetTopicAttributes`。

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

**AWS CLI**  
**为主题设置属性**  
以下 `set-topic-attributes` 示例为指定主题设置 `DisplayName` 属性。  

```
aws sns set-topic-attributes \
    --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --attribute-name DisplayName \
    --attribute-value MyTopicDisplayName
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[SetTopicAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-topic-attributes.html)*中的。

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

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](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);
        }
    }
}
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[SetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/SetTopicAttributes)*中的。

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

**适用于 JavaScript (v3) 的软件开发工具包**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples) 中查找完整示例，了解如何进行设置和运行。
在单独的模块中创建客户端并将其导出。  

```
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({});
```
导入 SDK 和客户端模块，然后调用 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;
};
```
+  有关更多信息，请参阅[《适用于 JavaScript 的 AWS SDK Developer Guide》](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topicsstttopicattributes)。
+  有关 API 的详细信息，请参阅 *适用于 JavaScript 的 AWS SDK API 参考[SetTopicAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/SetTopicAttributesCommand)*中的。

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

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](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.")
    }
}
```
+  有关 API 的详细信息，请参阅适用[SetTopicAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

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

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](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());
}
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[SetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/SetTopicAttributes)*中的。

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

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](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
```
+  有关更多信息，请参阅《适用于 Ruby 的 AWS SDK 开发人员指南》[https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-enable-resource.html](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-enable-resource.html)。
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[SetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/SetTopicAttributes)*中的。

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

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](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.
```
+  有关 API 的详细信息，请参阅适用[SetTopicAttributes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

# 使用配置传送状态日志 CloudFormation
<a name="msg-status-cloudformation"></a>

要`DeliveryStatusLogging`使用进行配置 CloudFormation，请使用 JSON 或 YAML 模板创建 CloudFormation 堆栈。有关更多信息，请参阅《 CloudFormation 用户指南》中的`AWS::SNS::Topic`资源`DeliveryStatusLogging`属性。以下是 JSON 和 YAML CloudFormation 模板的示例，这些模板用于创建新主题或使用 Amazon SQS `DeliveryStatusLogging` 协议的所有属性更新现有主题。

确保中引用的 IAM 角色`SuccessFeedbackRoleArn`并`FailureFeedbackRoleArn`具有所需的 CloudWatch 日志权限。

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

```
"Resources": {
    "MySNSTopic" : {
        "Type" : "AWS::SNS::Topic",
        "Properties" : {
            "TopicName" : "TestTopic",
            "DisplayName" : "TEST",
            "SignatureVersion" : "2",
            "DeliveryStatusLogging" : [{
                "Protocol": "sqs",
                "SuccessFeedbackSampleRate": "45",
                "SuccessFeedbackRoleArn": "arn:aws:iam::123456789012:role/SNSSuccessFeedback_test1",
                "FailureFeedbackRoleArn": "arn:aws: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:iam::123456789012:role/SNSSuccessFeedback_test1
         FailureFeedbackRoleArn: arn:aws:iam::123456789012:role/SNSFailureFeedback_test2
```

------