HUB
Sign inSign up

luisra51/cloudflare-exporter

By luisra51

•Updated 19 days ago

Prometheus exporter for Cloudflare analytics (Free plan supported)

Image
0

469

luisra51/cloudflare-exporter repository overview

 ██████╗███████╗    ███████╗██╗  ██╗██████╗  ██████╗ ██████╗ ████████╗███████╗██████╗
██╔════╝██╔════╝    ██╔════╝╚██╗██╔╝██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝██╔════╝██╔══██╗
██║     █████╗      █████╗   ╚███╔╝ ██████╔╝██║   ██║██████╔╝   ██║   █████╗  ██████╔╝
██║     ██╔══╝      ██╔══╝   ██╔██╗ ██╔═══╝ ██║   ██║██╔══██╗   ██║   ██╔══╝  ██╔══██╗
╚██████╗██║         ███████╗██╔╝ ██╗██║     ╚██████╔╝██║  ██║   ██║   ███████╗██║  ██║
 ╚═════╝╚═╝         ╚══════╝╚═╝  ╚═╝╚═╝      ╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝

⁠cloudflare-exporter

A Prometheus exporter for Cloudflare analytics that works with zones on the Free plan.

Go Version Docker Pulls CI License Multi-arch

📈 Traffic per zone and per host, security events, edge certificates, tunnels and Zero Trust for every zone and account your token can see, Free plan included.

⁠🤔 Why another Cloudflare exporter?

Popular Cloudflare exporters, such as lablabs/cloudflare-exporter⁠ and Cloudflare's own exporter, skip zones on the Free plan. They rely on GraphQL datasets (for example httpRequests1mGroups or firewallEventsAdaptiveGroups) that Free zones cannot query. Both are good tools for paid plans. This exporter covers the case they leave out: it reads the datasets that Free zones can query (httpRequests1hGroups, httpRequestsAdaptiveGroups, firewallEventsAdaptive), asks Cloudflare which fields each zone may use, and adds the richer ones when a zone's plan allows it.

On a Free-plan zonecloudflare-exporterExporters that skip Free zones
HTTP traffic (requests, bytes, cache, page views, visitors)✅❌ zone skipped
Requests by HTTP status code✅❌ zone skipped
Per-host requests by status class, near real time✅❌ zone skipped
Edge certificate expiry✅varies
Security (firewall) events by action and source✅❌ zone skipped
Cloudflare Tunnel health (status, connections, connectors)✅varies
Zero Trust: service token expiry, WARP devices, Gateway DNS, Access logins✅varies
Multi-arch image (amd64 + arm64)✅varies
Background collection (scrapes never call the API)✅varies

⁠✨ Features

  • 🆓 Free plan first: HTTP traffic from httpRequests1hGroups, per-host traffic from httpRequestsAdaptiveGroups and security events from firewallEventsAdaptive, all readable by Free zones
  • 🔍 Plan-aware: reads Cloudflare's GraphQL settings node per zone (enabled datasets, page sizes, available fields) and uses firewallEventsAdaptiveGroups, origin status, bytes and origin response time automatically when the zone may query them
  • 🌐 Auto-discovery: collects every zone the token can see, or an allowlist (CF_ZONES), minus exclusions (CF_EXCLUDE_ZONES)
  • 🏢 Account metrics: account-wide traffic from httpRequestsOverviewAdaptiveGroups
  • 🎯 Per-host traffic: requests per hostname and status class over a rolling 5-minute window, so you can alert on one host's 5xx rate within minutes; top N hosts plus other
  • 🔒 Edge certificates: earliest expiry and status of every certificate pack (Universal SSL included)
  • 🛡️ Zero Trust: Access service token expiry, WARP device counts by last-seen age and OS, Gateway DNS queries by resolver decision, Access logins by result
  • 🚇 Tunnels: status, edge connections per data center, connectors and their cloudflared versions for Cloudflare Tunnels and WARP Connectors (available on every plan)
  • ⚡ Background collection: Cloudflare is queried every SCRAPE_INTERVAL; /metrics serves the cache, so scrapes are instant and never spend API quota
  • 🧮 Bounded cardinality: countries capped to a top N plus other; status, HTTP version, action and source are small enumerations
  • ✂️ Exact counts on busy zones: raw security events are split into smaller windows when a page fills up, with a query budget and a truncated flag when that is not enough
  • 🩺 Self-monitoring: per-dataset up and last-success timestamps, API error counters, collection duration
  • 🔐 Safe by default: read-only token, never logged and never printed by --help
  • 🐳 Small image: static, distroless, non-root, linux/amd64 and linux/arm64
  • 🛑 Graceful shutdown and a /healthz endpoint

⁠☕ Support

If you like this project, consider buying me a coffee⁠ ☕💛 Buy Me A Coffee ⁠

⁠🚀 Quick start

⁠Docker
docker run -d --name cloudflare-exporter \
  -p 8080:8080 \
  -e CF_API_TOKEN=your-read-only-token \
  luisra51/cloudflare-exporter:latest

curl -s http://localhost:8080/metrics | grep '^cloudflare_'
⁠Docker Compose
services:
  cloudflare-exporter:
    image: luisra51/cloudflare-exporter:latest
    restart: unless-stopped
    ports:
      - "8080:8080"
    environment:
      CF_API_TOKEN: ${CF_API_TOKEN}
      # CF_ZONES: "<zone-id-1>,<zone-id-2>"   # optional allowlist
      SCRAPE_INTERVAL: 5m
      LOG_FORMAT: json
⁠Go
go install github.com/luisra51/cloudflare-exporter/cmd/cloudflare-exporter@latest
CF_API_TOKEN=your-read-only-token cloudflare-exporter

Or from source:

git clone https://github.com/luisra51/cloudflare-exporter.git
cd cloudflare-exporter
task build && CF_API_TOKEN=your-read-only-token ./bin/cloudflare-exporter
⁠Try it without a Cloudflare account

A fake Cloudflare API with synthetic data is bundled:

task run:fake
# then open http://localhost:8080/metrics

⁠🔑 API token

The exporter only needs read access.

  1. In the Cloudflare dashboard go to My Profile → API Tokens → Create Token.

  2. Choose Create Custom Token.

  3. Add these permissions, all set to Read:

    ScopePermissionUsed for
    ZoneZonezone discovery and plan (/zones)
    ZoneAnalyticsHTTP traffic (httpRequests1hGroups)
    ZoneFirewall Servicessecurity events
    AccountAccount Analyticsaccount-wide traffic
    AccountAccount Settingsaccount name
    AccountCloudflare Tunneltunnel metrics (optional)
    ZoneSSL and Certificatesedge certificate metrics (optional)
    AccountAccess: Service Tokensservice token expiry (optional)
    AccountZero TrustWARP device counts (optional)
  4. Under Zone Resources and Account Resources, include only what you want to monitor.

  5. Create the token and pass it as CF_API_TOKEN.

Without the account permissions, set CF_ACCOUNT_METRICS=false. The Cloudflare Tunnel permission is only needed for tunnel metrics: without it the exporter logs one warning, reports cloudflare_exporter_up{dataset="tunnels"} 0 and keeps collecting everything else (or set CF_TUNNEL_METRICS=false).

Every optional group works the same way: a missing permission produces one warning naming it, cloudflare_exporter_up{dataset="..."} 0, and no effect on the other metrics.

Feature groupFlagPermissions (all Read)dataset in cloudflare_exporter_up
Per-host trafficCF_HOST_METRICSZone → AnalyticshttpRequestsAdaptiveGroups
Edge certificatesCF_CERT_METRICSZone → SSL and Certificatescertificate_packs
TunnelsCF_TUNNEL_METRICSAccount → Cloudflare Tunneltunnels, tunnel_connectors
Service tokensCF_ZEROTRUST_METRICSAccount → Access: Service Tokensaccess_service_tokens
WARP devicesCF_ZEROTRUST_METRICSAccount → Zero Trustdevices
Gateway DNSCF_ZEROTRUST_METRICSAccount → Account Analytics (Gateway in use)gatewayResolverQueriesAdaptiveGroups
Access loginsCF_ZEROTRUST_METRICSAccount → Account Analytics (Access in use)accessLoginRequestsAdaptiveGroups

⁠⚙️ Configuration

Every setting is an environment variable and a flag; flags win. Prefer the environment variable for the token, since flags are visible in the process list.

Env varFlagDefaultDescription
CF_API_TOKEN--api-token— (required)Cloudflare API token
CF_ZONES--zonesall zones the token seesComma-separated zone IDs to collect
CF_EXCLUDE_ZONES--exclude-zones—Comma-separated zone IDs to skip
CF_ACCOUNTS--accountsaccounts of the discovered zonesComma-separated account IDs; restricts zone discovery and selects accounts for account metrics
LISTEN--listen:8080HTTP listen address
METRICS_PATH--metrics-path/metricsMetrics endpoint path
SCRAPE_INTERVAL--scrape-interval5mHow often to query Cloudflare in the background
CF_HOURLY_DELAY--hourly-delay10mWait this long after an hour ends before reporting it
CF_TOP_COUNTRIES--top-countries20Countries per zone; the rest are summed as country="other"; 0 disables country metrics
CF_FIREWALL_EVENTS--firewall-eventstrueCollect security events
CF_ACCOUNT_METRICS--account-metricstrueCollect account-level metrics
CF_TUNNEL_METRICS--tunnel-metricstrueCollect Cloudflare Tunnel health metrics
CF_HOST_METRICS--host-metricstrueCollect per-host traffic (httpRequestsAdaptiveGroups)
CF_HOST_EXACT_STATUS--host-exact-statusfalseAlso export per-host requests by exact status code
CF_TOP_HOSTS--top-hosts50Hosts per zone; the rest are summed as host="other"; 0 = no limit
CF_ADAPTIVE_WINDOW--adaptive-window5mLength of the rolling window for near-real-time data
CF_ADAPTIVE_DELAY--adaptive-delay3mHow long ago the rolling window ends, to let data arrive
CF_CERT_METRICS--cert-metricstrueCollect edge certificate pack metrics
CF_ZEROTRUST_METRICS--zerotrust-metricstrueCollect Zero Trust metrics
CF_DEVICES_INTERVAL--devices-interval1hHow often to re-read the WARP device list (it can be large)
CF_CONCURRENCY--concurrency4Maximum concurrent Cloudflare API requests
CF_HTTP_TIMEOUT--http-timeout30sTimeout per API request
CF_API_URL--api-urlhttps://api.cloudflare.com/client/v4API base URL (for testing)
LOG_LEVEL--log-levelinfodebug, info, warn, error
LOG_FORMAT--log-formattexttext or json
—--versionPrint version and exit
⁠Endpoints
PathDescription
/metricsPrometheus metrics (configurable with METRICS_PATH)
/healthzLiveness: always 200 with {"status":"ok","zone_discovery_succeeded":...,"last_collection":...}
/Small landing page

⁠⏱️ How hourly and near-real-time data work

  • Metrics describe the last complete hour, as gauges ("requests in that hour"), not counters.
  • The exporter waits CF_HOURLY_DELAY (default 10m) after an hour ends so Cloudflare can finish aggregating it. At 12:05 you see 10:00–11:00; from 12:10 you see 11:00–12:00.
  • The hour is re-read every SCRAPE_INTERVAL, so late data is picked up.
  • Each group of metrics has a *_window_start_timestamp_seconds gauge with the start of the hour it describes.
  • If a query fails, the last good values are kept and cloudflare_exporter_up{dataset="..."} drops to 0. Zones that disappear from discovery are removed.
  • Free zones get security events as raw rows (up to 10,000 per query) that the exporter counts. A full page makes it split the window in halves, down to one minute, with a budget of 32 queries per zone and cycle. If that is still not enough, cloudflare_zone_hourly_firewall_events_truncated is 1 and the count is a lower bound.
  • Tunnel, certificate, service token and device metrics are not hourly: they describe the state at the last collection cycle (devices: at the last CF_DEVICES_INTERVAL).
  • Per-host, Gateway DNS and Access login metrics use a rolling window instead: CF_ADAPTIVE_WINDOW (default 5 minutes) ending CF_ADAPTIVE_DELAY (default 3 minutes) ago, aligned to the minute, re-read every cycle. With defaults at 12:10:30 you see 12:02–12:07. Divide by cloudflare_zone_host_window_seconds for a per-second rate. Keep SCRAPE_INTERVAL at or below the window to avoid gaps.
  • These come from Cloudflare's adaptive (sampled) datasets, so counts are Cloudflare's estimates, not exact totals. Low-traffic hosts may show small integer jumps.
  • Requests go through a concurrency limit and are retried on HTTP 429/5xx. Cloudflare allows 300 GraphQL queries per 5 minutes per user; with defaults the exporter uses about 3–4 GraphQL queries per zone per cycle (hourly HTTP, security events, per-host traffic) plus three per account (account traffic, Gateway DNS, Access logins). REST calls (limit: 1,200 per 5 minutes) cover zones, certificate packs (one per zone), tunnels (one list per account plus one per tunnel), service tokens, and devices (pages of 1,000, once per CF_DEVICES_INTERVAL). Disable what you don't need if you have many zones.

⁠📊 Metrics

zone is the zone name and account the account name.

⁠Zone HTTP traffic (last complete hour)

All with labels zone and account.

MetricExtra labelsDescription
cloudflare_zone_hourly_window_start_timestamp_secondsStart of the hour the HTTP metrics describe
cloudflare_zone_hourly_requestsRequests
cloudflare_zone_hourly_cached_requestsRequests served from cache
cloudflare_zone_hourly_encrypted_requestsHTTPS requests
cloudflare_zone_hourly_bytesBytes sent to clients
cloudflare_zone_hourly_cached_bytesBytes served from cache
cloudflare_zone_hourly_encrypted_bytesBytes sent over HTTPS
cloudflare_zone_hourly_page_viewsPage views
cloudflare_zone_hourly_threatsRequests classified as threats
cloudflare_zone_hourly_unique_visitorsUnique visitor IPs
cloudflare_zone_hourly_requests_by_statusstatusRequests by edge response status
cloudflare_zone_hourly_requests_by_http_versionhttp_versionRequests by client HTTP protocol
cloudflare_zone_hourly_requests_by_countrycountryRequests by client country (top N + other)
cloudflare_zone_hourly_threats_by_countrycountryThreats by client country
cloudflare_zone_hourly_bytes_by_countrycountryBytes by client country
⁠Zone security events (last complete hour)

All with labels zone and account.

MetricExtra labelsDescription
cloudflare_zone_hourly_firewall_window_start_timestamp_secondsStart of the hour the security metrics describe
cloudflare_zone_hourly_firewall_eventsaction, sourceEvents by action (block, managed_challenge, log, ...) and source (firewallCustom, waf, securitylevel, ...)
cloudflare_zone_hourly_firewall_events_truncateddataset1 if the count hit the API row limit and is a lower bound
⁠Account HTTP traffic (last complete hour)
MetricLabelsDescription
cloudflare_account_hourly_window_start_timestamp_secondsaccount, account_idStart of the hour
cloudflare_account_hourly_requestsaccount, account_idRequests across all zones
cloudflare_account_hourly_cached_requestsaccount, account_idCached requests
cloudflare_account_hourly_bytesaccount, account_idBytes
cloudflare_account_hourly_cached_bytesaccount, account_idCached bytes
⁠Cloudflare Tunnels (current state)

Covers Cloudflare Tunnels (cfd_tunnel) and WARP Connectors (warp_connector) that are not deleted, in the same accounts as the account metrics. Read on every collection cycle from the REST API (/accounts/{id}/tunnels and /accounts/{id}/{type}/{tunnel}/connections, one call per tunnel; if that call fails, connections are taken from the list response and arch is unknown). All with labels account and tunnel (the tunnel name). The connector's public origin IP is never exported, by design.

MetricExtra labelsDescription
cloudflare_tunnel_infoaccount_id, tunnel_id, type, config_srcAlways 1; type is cfd_tunnel or warp_connector, config_src is cloudflare, local or unknown
cloudflare_tunnel_statusstatusState set: 1 for the current status (healthy, degraded, down, inactive), 0 for the others
cloudflare_tunnel_up1 if the status is healthy or degraded
cloudflare_tunnel_connectionsEdge connections
cloudflare_tunnel_connections_pending_reconnectConnections flagged as pending reconnect (Cloudflare has deprecated this flag; it may always be 0)
cloudflare_tunnel_connections_by_colocoloEdge connections by Cloudflare data center
cloudflare_tunnel_connectorsDistinct connectors (cloudflared / WARP Connector instances)
cloudflare_tunnel_connector_infoconnector_id, version, archAlways 1, one per connector
cloudflare_tunnel_active_since_timestamp_secondsWhen the tunnel last became active (absent if never)
cloudflare_tunnel_inactive_since_timestamp_secondsWhen the tunnel last became inactive (absent if Cloudflare reports none)
⁠Per-host traffic (rolling window, httpRequestsAdaptiveGroups)

All with labels zone and account. host is capped by CF_TOP_HOSTS, the rest summed as host="other". Counts are sampled estimates.

MetricExtra labelsDescription
cloudflare_zone_host_window_start_timestamp_secondsStart of the window
cloudflare_zone_host_window_secondsLength of the window
cloudflare_zone_host_requestshost, status_classRequests by edge status class (1xx…5xx, unknown)
cloudflare_zone_host_requests_by_statushost, statusRequests by exact edge status (only with CF_HOST_EXACT_STATUS=true)
cloudflare_zone_host_byteshostBytes sent to clients (only if the zone may query edgeResponseBytes)
cloudflare_zone_host_origin_5xx_requestshostRequests whose origin answered 5xx (only if the zone may query originResponseStatus)
cloudflare_zone_host_origin_requestshostRequests that reached the origin, originResponseStatus > 0 (only if the zone may query originResponseStatus)
cloudflare_zone_host_origin_response_time_secondshostAverage origin response time over the requests that reached the origin, weighted by count; absent for a host with no origin requests in the window (only if the zone may query originResponseDurationMs and originResponseStatus)
cloudflare_zone_host_truncated1 if the query hit the API row limit and counts are a lower bound

The optional fields are requested only when the zone's settings node lists them in availableFields; if Cloudflare still refuses, the query is retried with the base fields.

Requests that never reach the origin (cache hits, edge redirects, clients that close early) have originResponseStatus = 0 and Cloudflare reports their average origin time as -1. They are left out of the origin metrics, so cloudflare_zone_host_origin_response_time_seconds is the average over cloudflare_zone_host_origin_requests only.

⁠Edge certificates (/zones/{id}/ssl/certificate_packs?status=all)
MetricLabelsDescription
cloudflare_zone_certificate_packszone, accountCertificate packs of the zone (all statuses)
cloudflare_zone_certificate_pack_infozone, account, pack_id, type, status, certificate_authorityAlways 1
cloudflare_zone_certificate_pack_activezone, account, pack_id, type1 if the pack status is active
cloudflare_zone_certificate_pack_expiry_timestamp_secondszone, account, pack_id, type, statusEarliest expiry among the pack's certificates (absent if none reported)
⁠Zero Trust

Service tokens and devices are read from the REST API; Gateway DNS and Access logins from account-level GraphQL over the rolling window. No per-device data and no service token client IDs are exported.

MetricLabelsDescription
cloudflare_access_service_tokensaccountAccess service tokens
cloudflare_access_service_token_expiry_timestamp_secondsaccount, nameExpiry of each token
cloudflare_access_service_token_last_seen_timestamp_secondsaccount, nameLast use, when Cloudflare reports it
cloudflare_zerotrust_devicesaccountWARP devices
cloudflare_zerotrust_devices_by_last_seenaccount, last_seenDevices by time since last seen; exclusive buckets 24h, 7d, 30d, older, never
cloudflare_zerotrust_devices_by_osaccount, osDevices by device_type (windows, mac, linux, android, ios, chromeos)
cloudflare_zerotrust_window_start_timestamp_secondsaccountStart of the Gateway DNS / Access window
cloudflare_zerotrust_window_secondsaccountLength of that window
cloudflare_gateway_dns_queriesaccount, decision, decision_codeGateway DNS queries by resolver decision (sampled estimate); decision is the documented name (blockedByCategory, allowedOnNoPolicyMatch, blockedRule, ...) or unknown
cloudflare_access_loginsaccount, resultAccess login attempts, success or failure (sampled estimate)
⁠Metadata and exporter health
MetricLabelsDescription
cloudflare_zone_infozone, zone_id, account, account_id, plan, statusAlways 1; plan is free, pro, business, enterprise, ...
cloudflare_exporter_upscope, target, dataset1 if the last attempt succeeded; scope is zone, account or exporter; dataset is zones, settings, httpRequests1hGroups, firewallEvents, httpRequestsOverviewAdaptiveGroups, tunnels, tunnel_connectors, httpRequestsAdaptiveGroups, certificate_packs, access_service_tokens, devices, gatewayResolverQueriesAdaptiveGroups or accessLoginRequestsAdaptiveGroups
cloudflare_exporter_last_success_timestamp_secondsscope, target, datasetTime of the last success
cloudflare_exporter_api_errors_totalapi, operationFailed API calls (api = rest or graphql)
cloudflare_exporter_collections_totalresultCollection cycles: success, partial, failure
cloudflare_exporter_collection_duration_secondsDuration of the last cycle
cloudflare_exporter_last_collection_timestamp_secondsWhen the last cycle finished
cloudflare_exporter_zonesZones being collected
cloudflare_exporter_build_infoversion, revision, goversionAlways 1

Standard go_* and process_* metrics are exported too.

Sample output:

cloudflare_zone_info{accoun

Tag summary

Content type

Image

Digest

sha256:e84085509…

Size

5 MB

Last updated

19 days ago

docker pull luisra51/cloudflare-exporter