Choose the Signal Before Creating a Logging Job
A logging job is a delivery contract, not a debug switch. It names a dataset, a field list, a destination and an enable flag; Cloudflare then ships batches until you stop it. The dataset decides what evidence can exist, while the destination decides who can read it and how long it survives.
Start with the question the evidence must answer. A customer reports one bad request, a reviewer asks who changed a ruleset, and an operator wants to know why a Worker threw. Those are three datasets and three retention arguments, not one job with every field enabled.
Request evidence lives in http_requests. The dataset carries the Ray ID, edge and origin timestamps, host, path, status, TLS details and the security action when a rule matched. It is the right home for per-request forensics, and the most expensive one per unit of traffic.
Security decisions are a separate signal. firewall_events records the rule that matched and the action taken; it does not reproduce every request. When the question is why a request was blocked, the security dataset is smaller and more direct than the request log.
DNS and Worker telemetry answer different questions. dns_logs shows the name, type and response for a query; workers_trace_events shows an invocation's outcome and log lines. Neither substitutes for an HTTP request record, and one job cannot carry two datasets.
Account changes belong to the control plane. audit_logs_v2 records who changed what through the API or dashboard, with actor, action, resource and a Ray ID. It is account-scoped, it covers roughly 95% of products, and new jobs should target v2 rather than the older dataset.
Alerting is not a log. A notification policy watches an event and dispatches a message; it keeps no record you can query later. Use it to wake someone up, then use logs to explain what happened.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
Q{"Record or signal?"} -->|"record"| P{"Which plane?"}
Q -->|"signal"| N["Notification policy
alert type and destination"]
P -->|"request path"| H["http_requests
HTTP and TLS evidence"]
P -->|"name resolution"| D["dns_logs
query and response"]
P -->|"security decision"| W["firewall_events
action and rule ID"]
P -->|"application runtime"| K["workers_trace_events
outcome and logs"]
P -->|"account control"| A["audit_logs_v2
actor and resource"]
P -->|"none of these"| X["No dataset fits
instrument the app"]
H --> V{"Volume and fields
fit the budget?"}
D --> V
W --> V
K --> V
A --> V
V -->|"yes"| J["Create the job"]
V -->|"no"| F["Filter, sample, or
choose a smaller dataset"]
F --> J
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class Q,P,V primary;
class H,D,W,K,A secondary;
class J ok;
class N,F warn;
class X danger;
The flow separates a record from a signal. If the need is a durable record, choose the plane and then the dataset; if the need is a human response, choose an alert type and a destination. The budget check at the end is deliberate, because a dataset that fits the question but not the bill is not a viable choice.
TLS is not its own dataset. Handshake version and cipher evidence arrive as fields on request records, so choose the request dataset when the question is about TLS. Worker subrequests behave the same way: they appear as request records unless you merge them into the parent.
The diagram keeps the control plane visible. Request, DNS, security and Worker signals are produced by traffic; audit events are produced by account changes. They can share a bucket, but they should not share a prefix, a retention rule or a reader group.
Read the table as a budget and an ownership map. Each row answers a different question and bills a different dimension; the last column names who must delete the data. A dataset with no retention owner is a compliance problem waiting for its first audit.
| Signal | Dataset or surface | Question it answers | Volume driver | Retention owner |
|---|---|---|---|---|
| Request forensics | http_requests | Which request, path, status and Ray ID? | 1.5–3 kB per record; every request and subrequest | Destination lifecycle |
| DNS | dns_logs | Which name was queried, and what was answered? | One record per query; high fan-out | Destination lifecycle |
| Security | firewall_events | Which rule matched, and what action ran? | Security events, not every request | Destination lifecycle |
| Worker runtime | workers_trace_events | Which invocation failed, with what outcome? | One record per invocation or log line | Destination lifecycle |
| Account audit | audit_logs_v2 | Who changed what, from where? | API and dashboard writes; low volume | 18 months in Cloudflare, then Logpush |
| Alerting | Notifications | Should a human act now? | Event frequency, not bytes | Inbox or webhook only |
Volume is measured before compression and before storage. An HTTP request record is roughly 1.5–3 kB uncompressed, so a million requests a day is about 45–90 GB a month before gzip. Files arrive compressed at the destination, using roughly a tenth of that storage, but the Logpush bill follows uncompressed bytes delivered.
Cost has two layers. Logpush includes 25 GB a month for internal exports and 25 GB for external exports, then charges per additional GB; the destination charges for storage, requests and egress on its own schedule. R2 keeps egress out of the bill, which is why it is a common landing zone for high-volume request logs.
The field list is the first cost control. Every field adds bytes to every record, and sample_rate reduces records rather than fields. Filter first, sample second, and keep a small unsampled job for the requests that need forensics.
Entitlement is a set of gates, not one plan label. Logpush is available on all plans with usage-based pricing, but some alerts are narrower: the failing-job alert is Enterprise, health-check alerts need a Professional plan or higher, and load-balancing alerts come with the load-balancing purchase. Check the specific alert type before writing the policy.
A rule that never ships is not evidence. filter and filter_attack_traffic reduce volume at the source. Each one changes what the dataset can answer, so record the filter beside the job name.
Subrequest merging changes the record shape. merge_subrequests keeps a Worker's outbound calls attached to the parent request, which reduces duplicate records but makes each record larger.
Configure Logpush Destinations and Ownership Challenges
A destination is a string with credentials inside it. The job's destination_conf carries the bucket, path and authentication parameters; provider 5.28.1 marks it sensitive, but sensitivity only hides it from terminal output. Treat the string as a secret because the state file, a saved plan and a provider debug log can each contain it.
R2 is the shortest path when logs stay in Cloudflare. The destination uses the S3-compatible endpoint with an account ID, access key ID and secret access key; a date token creates daily prefixes. A token scoped to one bucket is enough, and the bucket should be private with no public custom domain.
S3 and GCS add provider-specific credentials. S3 grants write access to Cloudflare's IAM user or accepts a role with an external ID; GCS grants object administration to Cloudflare's service account. Both can use the ownership challenge, and both bring their own encryption and lifecycle controls.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
S["destination_conf
bucket, path, credentials"] --> C["Request ownership
challenge"]
C --> F["Challenge file written
ownership-challenge-*.txt"]
F --> R["Read token from bucket"]
R --> J["Create job
dataset, fields, token"]
J --> E["Set enabled = true"]
E --> D["Batches arrive
last_complete set"]
S -.-> X6["Destination change
new challenge required"]
C -.-> X1["Failure: no read access
token cannot be retrieved"]
F -.-> X2["Failure: token older than 7 days
request a new one"]
J -.-> X3["Failure: token bound to
another zone or destination"]
E -.-> X4["Failure: credentials rejected
error_message set"]
X4 -.-> X5["24 hours without delivery
job disabled, no backfill"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class S,C,J,E,D primary;
class F,R secondary;
class X1,X2,X3,X5 danger;
class X4,X6 warn;
The ownership challenge proves read access, not trust. Cloudflare writes an encrypted token to a file in the bucket, you read it, and you submit it with the job. The token expires after seven days and is bound to the account or zone, the destination fingerprint and the object type, so it cannot be replayed against a different bucket.
Terraform cannot finish the challenge in one apply. The cloudflare_logpush_ownership_challenge resource creates the file and returns its name, validity and message, but not the token. The practical sequence is apply, read the file with the cloud provider's CLI, then apply the job with the token supplied as a sensitive variable.
The logging resource is cloudflare_logpush_job. It owns the dataset, field list, destination and enable flag, while the challenge resource owns only the proof.
Delete the challenge file after the job exists. It is a temporary proof, not an artifact to keep; leaving it in the bucket adds a readable token to every later access review. The job's ownership_challenge argument is also sensitive and ends up in state, so rotate the destination credentials if either value leaks.
R2 and other S3-compatible endpoints do not need the challenge. They authenticate with keys, which is simpler to automate and easier to leak. The trade is explicit: fewer moving parts, but the destination string becomes the credential.
A destination change is a new proof. Editing the destination requires a fresh challenge and a job update with the new token; changing the dataset or the job name is not an in-place edit at all. Treat a dataset change as a new job with a new name and a deliberate cutover.
The enable flag is the delivery switch. Setting enabled = false stops new batches without deleting the job or its configuration; re-enabling resumes from the current time. Logpush has no backfill, so every minute disabled is evidence that will never exist.
Batch caps are part of the contract. A job can cap uncompressed bytes between 5 MB and 1 GB, the interval between 30 and 300 seconds, and records between 1,000 and 1,000,000; zero disables a cap. Smaller batches arrive sooner and produce more objects; larger batches reduce request overhead but increase the loss per failed upload.
The job reports a last success time. last_complete is the last batch Cloudflare delivered, and it stays empty until the first success. On a high-volume zone the first batch can take hours, so a slow start is not automatically a failure.
Failure has its own pair of fields. last_error is the last failure time, and error_message describes the current problem; both clear after a success. A job with no successful delivery for 24 hours is disabled, and the missing window cannot be recovered.
An update replaces the output object. A field removed from configuration can reset to its default because the API replaces the whole object rather than merging it. Keep the full output_options block in configuration and let the plan show the whole change, not a fragment.
A green apply only means the API accepted the configuration. It does not prove that the bucket accepted a batch or that the reader can open the object. Delivery is a separate check against the destination and the job's state, which is why the final section exercises it.
Protect Log Contents, Destination Secrets and Retention
Log content is production data. A request record can contain a customer's path, IP address, user agent and identity headers, and a security record can contain the rule and action that classified them. Decide which of those fields the question actually needs before the first batch arrives.
The URI is the biggest leak. ClientRequestURI includes the query string, while ClientRequestPath does not. Prefer the path when a query can carry a token, an email address or a session identifier, and fix the application so secrets stop appearing in URLs at all.
Identity fields are a deliberate choice. ClientIP is personal data in many jurisdictions, and request headers or cookies can carry session tokens. Custom fields are configured per zone and apply to every request job that processes that zone, so a field added for one investigation becomes available to all of them.
The Access user header needs its own field. If Access identity is part of the evidence, add the user header explicitly and include the request-headers field. It is not forwarded automatically, and a missing header looks like an anonymous request rather than a configuration gap.
Redaction is narrow. The built-in CVE-2021-44228 option replaces a specific log-injection sequence; it is not a general PII scrubber. Field selection, filters and destination-side controls are the real redaction tools, and a custom transformation belongs in the application or the pipeline that reads the logs.
Destination secrets sit in the job string. The destination configuration carries the R2 access key and secret, or the equivalent S3 or GCS credential material. The provider marks the field sensitive, but the value still enters state, so the state backend is part of the secret's blast radius.
The challenge token and webhook secret follow the same rule. The ownership challenge is stored with the job, and a generic webhook secret is stored with the destination. Both are sensitive fields, and both should be rotated after an access review or a state exposure.
State and plan files are the leak path. Sensitivity masks terminal output; it does not encrypt the state or remove values from a saved plan. A short list keeps the exposure visible:
- State — a remote backend with encryption, locking and tightly scoped access.
- Plan artifact — treat it as a secret when it contains destination or webhook values.
- CI log — disable provider request logging and redact variables before artifacts are uploaded.
Retention is a destination policy, not a Logpush setting. Logpush retries within an internal window and then drops the batch; it does not keep a searchable archive. The bucket's lifecycle rules, archive tier or the destination's own retention controls decide how long the evidence survives.
Give each retention class its own prefix. Short-lived request forensics, security review copies and audit evidence rarely share a lifetime. Separate prefixes make each lifecycle rule auditable and keep a cleanup job from deleting the one class that legal asked you to preserve.
Access is the real boundary. A private bucket with a least-privilege reader group is stronger than any field-level redaction. Keep the log bucket out of public custom domains, separate it from application content, and grant read access to the people who investigate rather than to everyone who deploys.
Deletion must be deliberate. Removing the job stops delivery but leaves the delivered objects; removing the bucket deletes the evidence. Put a destroy guard on any bucket that holds audit or security records, and make deletion a reviewed operation with an explicit retention decision.
Connect Request Evidence with a Terraform Change Record
A Ray ID is the join key, not the whole story. Cloudflare returns it in the response header and writes it into the request record, so one identifier can take you from a customer report to the exact log line. It identifies the request, not the rule version, the apply or the person who changed the configuration.
Capture the identifier at the edge. Send a request you control, record the response header, the event time, the host, the path and the status, and put those in the change record. Do not paste cookies, authorization headers or the full query string into the ticket; the identifier is enough to find the record later.
Terraform supplies the configuration identity. A ruleset exposes its ID, version and last-updated timestamp as read-only attributes, and the job exposes its ID. Publish those values from the root that manages them, so the change record names the exact configuration that was live, not a Git branch name.
Apply time comes from the audit trail. Audit Logs v2 records the API write with an actor, a resource, a timestamp and its own Ray ID. Use that timestamp as the apply evidence when it exists, and keep the pipeline's run time beside it when the two differ.
Request logs do not carry the ruleset version. This is the trap in most correlation stories: the request record has the rule ID and action but not the version of the ruleset that contained it. Correlate through the apply window and the rule ID, and state the inference rather than pretending the field exists.
The change record has six fields. Keep it small enough to review:
- Source revision — the commit SHA that produced the plan.
- Artifact — the digest or version of the deployed Worker or configuration bundle.
- Edge configuration — ruleset ID and version, job ID, and the apply window.
- Apply evidence — audit event time and audit Ray ID.
- Request evidence — request Ray ID, event time, host, sanitized path and status.
- Outcome — what the operator concluded and what changed next.
Sanitize before you store. A path without its query string, a status code and a Ray ID are usually safe; an IP address, a cookie or a raw header is not. If the investigation needs a sensitive field, keep it in the log bucket with restricted access and reference it by identifier in the ticket.
Correlation uses event time, not delivery time. The request record's edge timestamp is when the request happened; the object's upload time is when the batch arrived. A delivery delay changes when you can read the evidence, not when the event occurred, so compare the event timestamp with the apply window.
Review the record against the audit log. If the audit trail has no write event at the recorded time, the apply did not happen, used another account, or used a token whose events you cannot see. That is a more useful conclusion than a green pipeline badge.
Audit absence is not proof of no action. Audit Logs v2 does not record every read at general availability, and 4xx responses are outside its scope. Use the write events for change evidence, and use request logs for what visitors did.
Prove Delivery and Exercise a Harmless Alert
Delivery is proven at the destination. A successful apply says the API accepted the job; it does not say a batch arrived, that the object is readable or that the alert reached a human. The proof is a small set of observations: the job's last success, an object with the expected Ray ID, and a destination that reports a successful delivery.
Alerting uses two resources. cloudflare_notification_policy_webhooks stores the destination, and cloudflare_notification_policy binds an alert type to it.
A harmless alert needs a disposable cause. Do not test an alert by breaking a production origin or disabling a real job. Use a health check pointed at a reserved documentation address, filter the alert to that one check, and let it report unhealthy while no traffic depends on it.
The exercise uses a small set of disposable resources. A request job with a narrow field list, a webhook destination with a notification policy, and a health check that is unhealthy by design. The production job stays untouched, and every resource is named with a run suffix you can find and remove.
Verify observability delivery
Execution status: design-only. The commands and observations below were not run against a live account for this article. You perform the exercise with your own disposable names and keep the output; the evidence is yours, not a transcript.
Prerequisites. An account with Logpush enabled, a private R2 bucket, a public HTTPS endpoint for the webhook, a zone on a plan that includes health checks, and Terraform 1.17.1 with provider 5.28.1. The token needs logging, notification and health-check permissions, and the bucket needs a writer scoped to one prefix.
Permissions are separate grants. Logs Write creates the job and challenge, and Notifications Write creates the policy and webhook.
The exercise needs one more grant. Health Checks Write creates the disposable check, and the notification policy also needs account settings read access.
- Create the bucket and the request job with a narrow field list, a filter for a test host and path, and the R2 destination. If you use S3 or GCS, either use access keys or apply the ownership challenge first, read the token from the bucket, then apply the job with that token. Record the job ID and wait for the first batch.
- Send one request to the test path and record the
cf-rayresponse header, the event time, the host and the path without its query string. Wait for the object under the date prefix, then confirm the record carries the same Ray ID. - Read the job state and confirm the last success is set and the failure fields are empty. The first batch can take minutes on a small zone and hours on a very busy one; a slow first batch is not a failure by itself.
- Create a generic webhook destination with a secret, then create a notification policy for the health-check alert type. Filter it to the disposable check and the unhealthy trigger, and attach the webhook as the mechanism.
- Create the
cloudflare_healthcheckagainst192.0.2.1, a reserved documentation address, with a short interval. It will fail by design and should produce at least one alert; confirm the endpoint received the secret header and returned a success status. - Disable the job and note the last success time. Wait longer than one batch interval, confirm no new objects arrive, then re-enable it and confirm delivery resumes. The disabled window is missing by design and cannot be backfilled.
- Decommission in order: disable the job, wait for the final batch, destroy the job, delete any challenge file, revoke the destination credentials, then remove the webhook, policy and health check. Keep the bucket only if its lifecycle and access policy are part of the evidence.
| Check | Evidence | Pass looks like |
|---|---|---|
| Job accepted | terraform state show | Job ID present, enabled true, error fields empty |
| Delivery proof | job state and bucket listing | last_complete set and one object with the test Ray ID |
| Alert delivery | webhook resource and endpoint log | last_success set and cf-webhook-auth matches |
| Pause behavior | object listing before and after disable | No new objects while disabled |
| Cleanup | final plan | Empty plan, production job untouched |
Expected observation. The job shows a last success time, the bucket contains a record with the test Ray ID, and the webhook reports a successful delivery for the disposable health check. The health check itself reports unhealthy with a failure reason, which is the intended result rather than a production incident.
Failure checks. Read the symptom before changing the job.
| Symptom | Likely cause | Next check |
|---|---|---|
| Empty last success | Destination rejected credentials, bucket policy is wrong, or endpoint or region is incorrect | Re-read the job error and test the destination with the same credentials |
| Healthy job, no object | Date prefix or bucket is wrong | List the destination at the current date and confirm the job's prefix |
| No alert | Policy filter, alert type or webhook reachability is wrong | Check the webhook last success and the policy filter |
| Duplicate records | Subrequests were not merged or a second job covers the same dataset | Compare job filters and the merge setting |
Cost dimensions. The lab is cheap; the production job is not.
| Dimension | What it covers | Control |
|---|---|---|
| Logpush volume | Uncompressed bytes delivered, after the monthly allowance | Narrow fields, filter, sample |
| Destination storage | Objects, requests and egress on the provider's schedule | Lifecycle, private bucket, R2 for egress |
| Health checks | The disposable monitor and its subscription | Delete the check after the alert |
Cleanup. Delete the test objects, destroy the job, remove the webhook and policy, delete the health check, and run a final plan. Keep the production bucket's destroy guard and verify that the test did not change the production job's destination or enable flag.
References (checked 6 November 2026): Logpush, ownership challenge, API configuration, Logpush health, audit logs, notifications, webhooks, logpush_job, notification_policy, healthcheck, ruleset.
Next in the Series
In Terraform State on R2: Bootstrap, Locking and Recovery Evidence, we'll explore Evaluate the S3-compatible backend with exact client behavior and recovery requirements rather than copying a legacy snippet.