How to Enable Access Logging on S3 Buckets in AWS
To enable access logging on an AWS S3 bucket, set the
Logging configuration on the source bucket to send logs to a target bucket. This involves specifying the TargetBucket and optionally a TargetPrefix where logs will be stored.Syntax
The access logging configuration for an S3 bucket requires specifying the LoggingEnabled block with two main parts:
- TargetBucket: The name of the bucket where logs will be saved.
- TargetPrefix: (Optional) A folder prefix inside the target bucket to organize logs.
This configuration is applied to the source bucket whose access you want to log.
yaml
LoggingConfiguration:
LoggingEnabled:
TargetBucket: string
TargetPrefix: string # optionalExample
This example shows how to enable access logging on a bucket named my-source-bucket to send logs to my-log-bucket with a prefix logs/. It uses AWS CLI commands.
bash
aws s3api put-bucket-logging --bucket my-source-bucket --bucket-logging-status '{"LoggingEnabled": {"TargetBucket": "my-log-bucket", "TargetPrefix": "logs/"}}'Common Pitfalls
- Target bucket must exist: The bucket where logs are stored must already exist before enabling logging.
- Permissions: The target bucket must allow the source bucket to write logs. This requires a bucket policy granting
s3:PutObjectpermission. - Logging delay: Logs may take some time to appear after enabling logging.
- Logging to the same bucket: Avoid logging to the same bucket to prevent recursive logging.
json
Wrong (no permissions):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Principal": {"Service": "logging.s3.amazonaws.com"},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::my-log-bucket/logs/*"
}
]
}
Right (with correct permissions):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": "logging.s3.amazonaws.com"},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::my-log-bucket/logs/*"
}
]
}Quick Reference
Remember these key points when enabling S3 access logging:
- The
TargetBucketmust exist and be different from the source bucket. - Set a
TargetPrefixto organize logs inside the target bucket. - Grant
s3:PutObjectpermission tologging.s3.amazonaws.comon the target bucket. - Logs are delivered asynchronously and may take time to appear.
Key Takeaways
Enable access logging by configuring the source bucket to send logs to a target bucket.
Ensure the target bucket exists and has proper permissions for logging.
Use a target prefix to organize logs inside the target bucket.
Logs may take time to appear after enabling logging.
Avoid logging to the same bucket to prevent recursive logging.