an AWS SDK 또는 CLIPutBucketLogging와 함께 사용 - AWS SDK 코드 예제

AWS Doc SDK ExamplesWord AWS SDK 리포지토리에는 더 많은 GitHub 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

an AWS SDK 또는 CLIPutBucketLogging와 함께 사용

다음 코드 예제는 PutBucketLogging의 사용 방법을 보여 줍니다.

.NET
AWS SDK for .NET
참고

더 많은 on 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 세부 정보는 PutBucketLogging AWS SDK for .NET 참조의 API를 참조하세요.

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/" } }

로깅 서비스 보안 주체에 s3:PutObject 권한을 부여하려면 put-bucket-policy 명령이 필요합니다.

자세한 내용은 Amazon S3 사용 설명서의 Amazon S3 서버 액세스 로깅을 참조하세요.

예시 2: 단일 사용자에게만 액세스 로깅에 대한 버킷 정책을 설정하려면

다음 put-bucket-logging 예제에서는 MyBucket에 대한 로깅 정책을 설정합니다. AWS 사용자 bob@example.com은 로그 파일을 완전히 제어할 수 있으며 다른 사람은 액세스할 수 없습니다. 먼저 put-bucket-acl을 사용하여 S3 권한을 부여합니다.

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" } ] } }

S3의 로그 전달 시스템에 필수 권한(write 및 read-acp 권한)을 부여하려면 put-bucket-acl 명령이 필요합니다.

자세한 내용은 Amazon S3 개발자 안내서의 Amazon S3 서버 액세스 로깅을 참조하세요.

  • API 세부 정보는 AWS CLI 명령 참조PutBucketLogging를 참조하세요.