Trong thời đại số hóa, việc theo dõi và phân tích log là yếu tố then chốt giúp doanh nghiệp đảm bảo hiệu suất, bảo mật và khả năng quan sát (observability) của hệ thống. Cloudflare LogPush là giải pháp enterprise-grade cho phép streaming log gần như real-time từ Cloudflare đến các hệ thống lưu trữ của bạn. Bài viết này sẽ hướng dẫn chi tiết cách triển khai LogPush với AWS S3, phân tích ưu nhược điểm của từng phương pháp và cung cấp best practices cho việc implementation.
LogPush là gì?
Cloudflare LogPush là dịch vụ gửi log theo batch càng nhanh càng tốt, không có kích thước batch tối thiểu, có khả năng gửi file nhiều lần trong một phút. Điều này cho phép Cloudflare cung cấp thông tin gần như real-time với kích thước file nhỏ hơn, giúp việc xử lý và phân tích log hiệu quả hơn.
Đặc điểm chính của LogPush
- Real-time Streaming: Log được gửi ngay khi có sẵn, không cần chờ đợi
- Flexible Batch Size: Có thể cấu hình kích thước batch qua API
- No Storage: LogPush không lưu trữ log, chỉ forward đến destination
- Enterprise Only: Chỉ khả dụng cho gói Enterprise
- Giới hạn: Tối đa 4 LogPush jobs cho mỗi zone
Kiến trúc tổng quan
┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Cloudflare │────────▶│ LogPush Service │────────▶│ AWS S3 Bucket │
│ Edge Network │ Logs │ │ Stream │ │
└─────────────────┘ └──────────────────┘ └──────────────────┘
│
▼
┌──────────────────┐
│ Configuration │
│ - Dashboard │
│ - API │
└──────────────────┘
Hai phương pháp triển khai LogPush
Phương pháp 1: Cấu hình qua Cloudflare Dashboard
Đây là phương pháp đơn giản nhất, phù hợp cho các team không yêu cầu automation phức tạp.
Workflow triển khai
AWS Team chuẩn bị infrastructure:
# Tạo S3 bucket
aws s3 mb s3://sandbox-cloudflare-logs --region ap-northeast-1
# Tạo IAM policy
cat > cloudflare-logpush-policy.json << EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::sandbox-cloudflare-logs/*"
}
]
}
EOF
# Tạo IAM user và attach policy
aws iam create-user --user-name cloudflare-logpush-user
aws iam put-user-policy --user-name cloudflare-logpush-user \
--policy-name CloudflareLogPushPolicy \
--policy-document file://cloudflare-logpush-policy.json
# Tạo access keys
aws iam create-access-key --user-name cloudflare-logpush-user
Cấu hình S3 Bucket Policy:Cloudflare sử dụng AWS IAM để truy cập S3 bucket của bạn. IAM user của Cloudflare cần quyền PutObject cho bucket.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudflareLogPush",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::391854517948:user/cloudflare-logpush"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::sandbox-cloudflare-logs/waf/*"
}
]
}
Cloudflare Team cấu hình qua Dashboard:
- Đăng nhập Cloudflare Dashboard
- Navigate: Analytics & Logs > Logpush
- Chọn "Create a Logpush job"
- Cấu hình destination với thông tin S3
- Verify ownership thông qua challenge token
- Chọn dataset và fields cần log
- Enable job
Ưu điểm
- ✅ Đơn giản, không cần technical expertise
- ✅ GUI trực quan
- ✅ Ít rủi ro về security (không expose API token)
- ✅ Phù hợp cho POC hoặc môi trường nhỏ
Nhược điểm
- ❌ Không thể automation
- ❌ Phụ thuộc vào Cloudflare team
- ❌ Khó scale khi có nhiều zones
- ❌ Manual process dễ gây lỗi
Phương pháp 2: Automation qua Cloudflare API
Phương pháp này cho phép automation hoàn toàn và phù hợp cho môi trường production.
Prerequisites
Tạo API Token với quyền phù hợp:Cần ít nhất một trong các quyền: Logs Write
# Verify token
curl "https://api.cloudflare.com/client/v4/user/tokens/verify" \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
Setup environment variables:
export CFZONEID="your-zone-id"
export CFTOKEN="your-api-token"
export AWSACCESSKEY="your-aws-access-key"
export AWSSECRETKEY="your-aws-secret-key"
export S3_BUCKET="sandbox-cloudflare-logs"
export AWS_REGION="ap-northeast-1"
Implementation chi tiết
Kiểm tra LogPush jobs hiện tại:
curl -X GET "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" | jq '.'
Tạo Ownership Challenge:Challenge file sẽ được ghi vào destination, và filename sẽ có trong response
RESPONSE=$(curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/ownership" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data "{
\"destination_conf\": \"s3://${S3_BUCKET}/waf?region=${AWS_REGION}&access-key-id=${AWSACCESSKEY}&secret-access-key=${AWSSECRETKEY}\"
}")
OWNERSHIP_TOKEN=$(echo $RESPONSE | jq -r '.result.filename')
echo "Ownership challenge file: $OWNERSHIP_TOKEN"
Đọc ownership token từ S3:
# Download và đọc challenge file
aws s3 cp s3://${S3_BUCKET}/${OWNERSHIP_TOKEN} ./challenge.txt
CHALLENGE_TOKEN=$(cat challenge.txt)
Tạo LogPush Job với đầy đủ configuration:
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data "{
\"name\": \"production-waf-logs\",
\"destination_conf\": \"s3://${S3_BUCKET}/waf?region=${AWS_REGION}&access-key-id=${AWSACCESSKEY}&secret-access-key=${AWSSECRETKEY}\",
\"dataset\": \"firewall_events\",
\"enabled\": true,
\"frequency\": \"high\",
\"output_options\": {
\"field_names\": [
\"Action\",
\"ClientASN\",
\"ClientCountry\",
\"ClientIP\",
\"ClientRequestHost\",
\"ClientRequestMethod\",
\"ClientRequestPath\",
\"ClientRequestProtocol\",
\"ClientRequestUserAgent\",
\"Datetime\",
\"EdgeResponseStatus\",
\"Kind\",
\"MatchIndex\",
\"Metadata\",
\"OriginResponseStatus\",
\"OriginatorRayID\",
\"RayID\",
\"RuleID\",
\"Source\"
],
\"timestamp_format\": \"rfc3339\"
},
\"ownership_challenge\": \"${CHALLENGE_TOKEN}\"
}" | jq '.'
Verify và Monitor Job:
# Get job details
JOB_ID="your-job-id"
curl -X GET "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs/${JOB_ID}" \
-H "Authorization: Bearer ${CFTOKEN}" | jq '.result | {
id: .id,
enabled: .enabled,
last_complete: .last_complete,
last_error: .last_error,
error_message: .error_message
}'
Advanced Configuration Chi Tiết
1. Filtering - Lọc logs theo điều kiện cụ thể
LogPush cho phép bạn filter logs trước khi gửi đến destination, giúp giảm bandwidth và storage costs. Filters sử dụng Wireshark-like syntax.
Basic Filter Syntax
{
"filter": "{\"where\":{\"key\":\"ClientCountry\",\"operator\":\"eq\",\"value\":\"US\"}}"
}
Complex Filter với Multiple Conditions
# Filter: Chỉ lấy logs từ US hoặc UK với status code >= 400
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "filtered-error-logs",
"destination_conf": "s3://bucket/path",
"dataset": "http_requests",
"filter": "{\"where\":{\"or\":[{\"and\":[{\"key\":\"ClientCountry\",\"operator\":\"eq\",\"value\":\"US\"},{\"key\":\"EdgeResponseStatus\",\"operator\":\"geq\",\"value\":\"400\"}]},{\"and\":[{\"key\":\"ClientCountry\",\"operator\":\"eq\",\"value\":\"UK\"},{\"key\":\"EdgeResponseStatus\",\"operator\":\"geq\",\"value\":\"400\"}]}]}}",
"enabled": true
}'
Filter Operators Được Hỗ Trợ
| Operator | Description | Example |
|---|---|---|
| eq | Equals | "operator":"eq","value":"US" |
| neq | Not equals | "operator":"neq","value":"bot" |
| lt | Less than | "operator":"lt","value":"500" |
| lte | Less than or equal | "operator":"lte","value":"500" |
| gt | Greater than | "operator":"gt","value":"0" |
| gte | Greater than or equal | "operator":"gte","value":"400" |
| contains | String contains | "operator":"contains","value":"admin" |
| in | Value in array | "operator":"in","value":["US","UK","CA"] |
2. Sampling Rate - Lấy mẫu logs
Sampling cho phép bạn chỉ gửi một phần trăm logs, hữu ích cho high-traffic sites.
# Chỉ lấy 10% logs (0.1 = 10%)
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "sampled-logs",
"destination_conf": "s3://bucket/path",
"dataset": "http_requests",
"output_options": {
"field_names": ["ClientIP", "EdgeResponseStatus", "ClientRequestHost"],
"sample_rate": 0.1
}
}'
3. Max Upload Parameters - Kiểm soát batch size
Cấu hình kích thước và số lượng records tối đa cho mỗi batch upload.
curl -X PUT "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs/${JOB_ID}" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"max_upload_bytes": 5000000, # 5MB per file
"max_upload_records": 10000, # 10k records per file
"max_upload_interval_seconds": 30 # Upload every 30 seconds
}'
4. Output Options - Tùy chỉnh format và fields
Timestamp Formats
{
"output_options": {
"timestamp_format": "rfc3339", // 2024-01-15T10:30:00Z
// hoặc "unix" // 1705318200
// hoặc "unixnano" // 1705318200000000000
}
}
Custom Field Selection cho từng use case
# Security monitoring - Focus on threat indicators
SECURITY_FIELDS='[
"ClientIP",
"ClientASN",
"ClientCountry",
"ClientRequestUserAgent",
"EdgeResponseStatus",
"WAFAction",
"WAFRuleID",
"WAFRuleMessage",
"SecurityLevel",
"RayID"
]'
# Performance monitoring - Focus on latency và errors
PERFORMANCE_FIELDS='[
"EdgeStartTimestamp",
"EdgeEndTimestamp",
"OriginResponseTime",
"EdgeResponseStatus",
"CacheStatus",
"EdgeResponseBytes",
"ClientRequestMethod",
"ClientRequestURI"
]'
# Bot detection - Focus on bot signals
BOT_FIELDS='[
"ClientIP",
"ClientRequestUserAgent",
"BotScore",
"BotScoreSrc",
"BotTags",
"JA3Hash",
"ClientRequestHeaders"
]'
5. CVE-2021-44228 (Log4j) Protection
Bảo vệ against Log4Shell vulnerability bằng cách replace ${ với x{:
curl -X PUT "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs/${JOB_ID}" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"output_options": {
"CVE-2021-44228": true,
"field_names": ["ClientRequestUserAgent", "ClientRequestURI", "ClientRequestHeaders"]
}
}'
6. Multiple Destinations Configuration
Gửi logs đến nhiều destinations đồng thời (tối đa 4 jobs per zone):
# Job 1: Full logs to S3 for long-term storage
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
--data '{
"name": "s3-full-logs",
"destination_conf": "s3://archive-bucket/full/",
"dataset": "http_requests",
"frequency": "low"
}'
# Job 2: Error logs to Splunk for alerting
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
--data '{
"name": "splunk-errors",
"destination_conf": "splunk://splunk.example.com",
"dataset": "http_requests",
"filter": "{\"where\":{\"key\":\"EdgeResponseStatus\",\"operator\":\"gte\",\"value\":\"400\"}}",
"frequency": "high"
}'
# Job 3: WAF events to SIEM
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
--data '{
"name": "siem-waf-events",
"destination_conf": "https://siem.example.com/webhook",
"dataset": "firewall_events",
"frequency": "high"
}'
Các Kịch Bản Sử Dụng LogPush Trong Thực Tế
Kịch bản 1: Security Operations Center (SOC) Monitoring
Yêu cầu: Team SOC cần monitor real-time các threats và attacks.
Implementation:
# Setup WAF logs với high frequency cho immediate threat detection
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "soc-waf-monitoring",
"destination_conf": "s3://soc-bucket/waf/",
"dataset": "firewall_events",
"frequency": "high",
"output_options": {
"field_names": [
"Action",
"ClientIP",
"ClientCountry",
"ClientASN",
"ClientRequestHost",
"ClientRequestPath",
"ClientRequestMethod",
"ClientRequestUserAgent",
"Datetime",
"RuleID",
"RuleMessage",
"Source",
"RayID"
],
"timestamp_format": "rfc3339"
},
"filter": "{\"where\":{\"key\":\"Action\",\"operator\":\"in\",\"value\":[\"block\",\"challenge\",\"jschallenge\"]}}"
}'
Use case:
- Real-time alerting on blocked requests
- Threat intelligence gathering
- Attack pattern analysis
- IP reputation tracking
Kịch bản 2: Compliance và Audit Requirements
Yêu cầu: Lưu trữ logs 7 năm theo quy định GDPR/PCI-DSS.
Implementation:
# Setup với compression và encryption cho long-term storage
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "compliance-audit-logs",
"destination_conf": "s3://compliance-bucket/audit/?sse=AES256",
"dataset": "http_requests",
"frequency": "low",
"output_options": {
"field_names": [
"ClientIP",
"ClientRequestHost",
"ClientRequestMethod",
"ClientRequestURI",
"EdgeResponseStatus",
"EdgeStartTimestamp",
"EdgeEndTimestamp",
"RayID",
"EdgeServerIP",
"ClientCountry"
]
}
}'
Use case:
- PCI-DSS compliance (track all access to payment pages)
- GDPR compliance (user data access logs)
- Internal audit trails
- Forensic analysis
Kịch bản 3: Performance Monitoring và SLA Tracking
Yêu cầu: Monitor website performance và track SLA metrics.
Implementation:
# Focus on performance metrics
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "performance-metrics",
"destination_conf": "s3://metrics-bucket/performance/",
"dataset": "http_requests",
"output_options": {
"field_names": [
"ClientRequestHost",
"ClientRequestPath",
"EdgeStartTimestamp",
"EdgeEndTimestamp",
"EdgeTimeToFirstByteMs",
"OriginResponseTime",
"EdgeResponseStatus",
"CacheStatus",
"EdgeResponseBytes",
"EdgeResponseCompressionRatio"
],
"sample_rate": 0.01
},
"filter": "{\"where\":{\"key\":\"ClientRequestHost\",\"operator\":\"eq\",\"value\":\"api.example.com\"}}"
}'
Use case:
- API response time monitoring
- Cache hit ratio analysis
- Bandwidth optimization
- Error rate tracking
Kịch bản 4: Bot Traffic Analysis
Yêu cầu: Phân tích bot traffic để optimize bot management rules.
Implementation:
# Bot-specific logging
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "bot-analysis",
"destination_conf": "s3://analytics-bucket/bots/",
"dataset": "http_requests",
"output_options": {
"field_names": [
"ClientIP",
"ClientRequestUserAgent",
"BotScore",
"BotScoreSrc",
"BotTags",
"BotManagement",
"JA3Hash",
"ClientRequestPath",
"EdgeResponseStatus"
]
},
"filter": "{\"where\":{\"key\":\"BotScore\",\"operator\":\"gt\",\"value\":\"0\"}}"
}'
Use case:
- Identify good bots vs bad bots
- Fine-tune bot management rules
- Analyze crawler behavior
- Detect bot patterns
Kịch bản 5: DDoS Mitigation và Analysis
Yêu cầu: Quick detection và analysis của DDoS attacks.
Implementation:
# High-frequency logging during attacks
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "ddos-mitigation",
"destination_conf": "s3://ddos-bucket/attacks/",
"dataset": "spectrum_events",
"frequency": "high",
"output_options": {
"field_names": [
"Application",
"ClientAsn",
"ClientIP",
"ColoCode",
"Event",
"IPProtocol",
"OriginIP",
"Status",
"Timestamp"
]
}
}'
Use case:
- Real-time attack detection
- Attack source analysis
- Mitigation effectiveness tracking
- Post-attack forensics
Kịch bản 6: Content Delivery Optimization
Yêu cầu: Optimize CDN performance và content delivery.
Implementation:
# CDN optimization metrics
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "cdn-optimization",
"destination_conf": "s3://cdn-bucket/metrics/",
"dataset": "http_requests",
"output_options": {
"field_names": [
"CacheCacheStatus",
"CacheResponseBytes",
"CacheResponseStatus",
"CacheTieredFill",
"ClientRequestBytes",
"ClientRequestHost",
"ClientRequestPath",
"EdgeColoCode",
"EdgeResponseBytes",
"EdgeResponseContentType"
],
"sample_rate": 0.05
}
}'
Use case:
- Cache hit ratio optimization
- Bandwidth usage analysis
- Geographic distribution insights
- Content type performance
Best Practices và Recommendations
1. Security Best Practices
- Rotate API tokens định kỳ: Implement token rotation mỗi 90 ngày
- Use IAM roles thay vì access keys khi possible
- Enable S3 encryption: Sử dụng SSE-S3 hoặc SSE-KMS
- Implement least privilege: Chỉ grant quyền cần thiết
2. Performance Optimization
- Partition S3 data: Sử dụng prefix phân chia theo ngày/giờ
- Enable S3 Transfer Acceleration cho cross-region replication
- Compress logs: Sử dụng gzip compression (mặc định)
- Optimize batch size: Điều chỉnh dựa trên volume
Kịch bản 7: Multi-tenant SaaS Platform Monitoring
Yêu cầu: Monitor usage và performance cho từng tenant.
Implementation:
# Per-tenant logging với custom headers
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CFZONEID}/logpush/jobs" \
-H "Authorization: Bearer ${CFTOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "saas-tenant-logs",
"destination_conf": "s3://saas-bucket/tenants/",
"dataset": "http_requests",
"output_options": {
"field_names": [
"ClientRequestHeaders",
"ClientRequestHost",
"ClientRequestPath",
"EdgeResponseStatus",
"EdgeResponseBytes",
"EdgeRequestCount",
"ClientIP"
]
}
}'
Use case:
- Per-tenant usage billing
- Tenant-specific SLA monitoring
- Resource allocation optimization
- Abuse detection per tenant
Comparison Matrix: Dashboard vs API
| Tiêu chí | Dashboard | API |
|---|---|---|
| Độ phức tạp | Thấp | Cao |
| Automation | Không | Có |
| Scalability | Hạn chế | Cao |
| Error handling | Manual | Programmatic |
| Version control | Không | Có (IaC) |
| Audit trail | Limited | Full |
| Initial setup time | 15 phút | 1-2 giờ |
| Maintenance | Manual | Automated |
| Phù hợp cho | POC, Small teams | Production, DevOps |
Kết luận
Cloudflare LogPush là giải pháp mạnh mẽ cho việc streaming logs real-time đến AWS S3. Việc lựa chọn giữa Dashboard và API approach phụ thuộc vào:
- Use Dashboard khi: Team nhỏ, POC, không yêu cầu automation
- Use API khi: Production environment, cần automation, multiple zones
Với proper implementation và monitoring, LogPush có thể cung cấp valuable insights cho security, performance optimization và compliance requirements. Investment vào automation ban đầu sẽ pay off trong long-term với reduced operational overhead và improved reliability.
