搭PutBucketLogging配 AWS 開發套件或 CLI 使用 - AWS SDK 程式碼範例

AWS 文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

PutBucketLogging配 AWS 開發套件或 CLI 使用

下列程式碼範例會示範如何使用PutBucketLogging

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

using System; using System.IO; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; using Microsoft.Extensions.Configuration; /// <summary> /// This example shows how to enable logging on an Amazon Simple Storage /// Service (Amazon S3) bucket. You need to have two Amazon S3 buckets for /// this example. The first is the bucket for which you wish to enable /// logging, and the second is the location where you want to store the /// logs. /// </summary> public class ServerAccessLogging { private static IConfiguration _configuration = null!; public static async Task Main() { LoadConfig(); string bucketName = _configuration["BucketName"]; string logBucketName = _configuration["LogBucketName"]; string logObjectKeyPrefix = _configuration["LogObjectKeyPrefix"]; string accountId = _configuration["AccountId"]; // If the AWS Region defined for your default user is different // from the Region where your Amazon S3 bucket is located, // pass the Region name to the Amazon S3 client object's constructor. // For example: RegionEndpoint.USWest2 or RegionEndpoint.USEast2. IAmazonS3 client = new AmazonS3Client(); try { // Update bucket policy for target bucket to allow delivery of logs to it. await SetBucketPolicyToAllowLogDelivery( client, bucketName, logBucketName, logObjectKeyPrefix, accountId); // Enable logging on the source bucket. await EnableLoggingAsync( client, bucketName, logBucketName, logObjectKeyPrefix); } catch (AmazonS3Exception e) { Console.WriteLine($"Error: {e.Message}"); } } /// <summary> /// This method grants appropriate permissions for logging to the /// Amazon S3 bucket where the logs will be stored. /// </summary> /// <param name="client">The initialized Amazon S3 client which will be used /// to apply the bucket policy.</param> /// <param name="sourceBucketName">The name of the source bucket.</param> /// <param name="logBucketName">The name of the bucket where logging /// information will be stored.</param> /// <param name="logPrefix">The logging prefix where the logs should be delivered.</param> /// <param name="accountId">The account id of the account where the source bucket exists.</param> /// <returns>Async task.</returns> public static async Task SetBucketPolicyToAllowLogDelivery( IAmazonS3 client, string sourceBucketName, string logBucketName, string logPrefix, string accountId) { var resourceArn = @"""arn:aws:s3:::" + logBucketName + "/" + logPrefix + @"*"""; var newPolicy = @"{ ""Statement"":[{ ""Sid"": ""S3ServerAccessLogsPolicy"", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""logging.s3.amazonaws.com"" }, ""Action"": [""s3:PutObject""], ""Resource"": [" + resourceArn + @"], ""Condition"": { ""ArnLike"": { ""aws:SourceArn"": ""arn:aws:s3:::" + sourceBucketName + @""" }, ""StringEquals"": { ""aws:SourceAccount"": """ + accountId + @""" } } }] }"; Console.WriteLine($"The policy to apply to bucket {logBucketName} to enable logging:"); Console.WriteLine(newPolicy); PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest { BucketName = logBucketName, Policy = newPolicy, }; await client.PutBucketPolicyAsync(putRequest); Console.WriteLine("Policy applied."); } /// <summary> /// This method enables logging for an Amazon S3 bucket. Logs will be stored /// in the bucket you selected for logging. Selected prefix /// will be prepended to each log object. /// </summary> /// <param name="client">The initialized Amazon S3 client which will be used /// to configure and apply logging to the selected Amazon S3 bucket.</param> /// <param name="bucketName">The name of the Amazon S3 bucket for which you /// wish to enable logging.</param> /// <param name="logBucketName">The name of the Amazon S3 bucket where logging /// information will be stored.</param> /// <param name="logObjectKeyPrefix">The prefix to prepend to each /// object key.</param> /// <returns>Async task.</returns> public static async Task EnableLoggingAsync( IAmazonS3 client, string bucketName, string logBucketName, string logObjectKeyPrefix) { Console.WriteLine($"Enabling logging for bucket {bucketName}."); var loggingConfig = new S3BucketLoggingConfig { TargetBucketName = logBucketName, TargetPrefix = logObjectKeyPrefix, }; var putBucketLoggingRequest = new PutBucketLoggingRequest { BucketName = bucketName, LoggingConfig = loggingConfig, }; await client.PutBucketLoggingAsync(putBucketLoggingRequest); Console.WriteLine($"Logging enabled."); } /// <summary> /// Loads configuration from settings files. /// </summary> public static void LoadConfig() { _configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally, load local settings. .Build(); } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考PutBucketLogging中的。

CLI
AWS CLI

範例 1:若要設定值區政策記錄

下列put-bucket-logging範例會設定的記錄原則MyBucket。首先,使用put-bucket-policy命令授予值區政策中的記錄服務主體權限。

aws s3api put-bucket-policy \ --bucket MyBucket \ --policy file://policy.json

policy.json 的內容:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "S3ServerAccessLogsPolicy", "Effect": "Allow", "Principal": {"Service": "logging.s3.amazonaws.com"}, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::MyBucket/Logs/*", "Condition": { "ArnLike": {"aws:SourceARN": "arn:aws:s3:::SOURCE-BUCKET-NAME"}, "StringEquals": {"aws:SourceAccount": "SOURCE-AWS-ACCOUNT-ID"} } } ] }

若要套用記錄原則,請使用put-bucket-logging

aws s3api put-bucket-logging \ --bucket MyBucket \ --bucket-logging-status file://logging.json

logging.json 的內容:

{ "LoggingEnabled": { "TargetBucket": "MyBucket", "TargetPrefix": "Logs/" } }

需要此put-bucket-policy命令才能將s3:PutObject權限授與記錄服務主體。

如需詳細資訊,請參閱 Amazon S3 使用者指南中的 Amazon S3 伺服器存取日誌

範例 2:若要設定值區政策,以便只記錄單一使用者的存取權

下列put-bucket-logging範例會設定的記錄原則MyBucket。 AWS 使用者 bob@example.com 將擁有對記錄檔的完全控制權,而且沒有其他人擁有任何存取權。首先,授與 S3 許可put-bucket-acl

aws s3api put-bucket-acl \ --bucket MyBucket \ --grant-write URI=http://acs.amazonaws.com/groups/s3/LogDelivery \ --grant-read-acp URI=http://acs.amazonaws.com/groups/s3/LogDelivery

然後使用套用記錄原則put-bucket-logging

aws s3api put-bucket-logging \ --bucket MyBucket \ --bucket-logging-status file://logging.json

logging.json 的內容:

{ "LoggingEnabled": { "TargetBucket": "MyBucket", "TargetPrefix": "MyBucketLogs/", "TargetGrants": [ { "Grantee": { "Type": "AmazonCustomerByEmail", "EmailAddress": "bob@example.com" }, "Permission": "FULL_CONTROL" } ] } }

需要該put-bucket-acl命令才能授予 S3 的日誌傳遞系統必要的權限(寫入和讀取 ACP 權限)。

如需詳細資訊,請參閱 Amazon S3 開發人員指南中的 Amazon S3 伺服器存取日誌

  • 如需 API 詳細資訊,請參閱AWS CLI 命令參考PutBucketLogging中的。