Generated banner for Cloud Logging Finops
Generated logo for Cloud Logging Finops

Cloud Logging Finops

GoogleOfficialPublished by Google

  • Skill
  • Content generator
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Audits Cloud Logging costs for a Google Cloud project: the charges for log entries written to log buckets, the services, log streams and severities that drive them, and the log sinks that route them. Reconciles Cloud Billing export costs with Cloud Monitoring volume metrics, and generates a FinOps report with charts and copy-paste exclusion filters. Use when auditing Cloud Logging spend, finding logging waste, identifying top logging contributors, generating log cost reduction reports, or creating log sink exclusion filters. Don't use for querying log entries (use cloud-logging-query-generation), configuring Cloud Monitoring alerts, or querying metrics/traces.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The cloud-logging-finops skill provides a comprehensive audit of Google Cloud Logging expenses. It reconciles Cloud Billing export data with Cloud Monitoring volume metrics to provide a clear picture of where logging costs originate, including breakdowns by service, log stream, and severity. The skill generates a detailed FinOps report featuring charts and specific, copy-pasteable exclusion filters to help users reduce unnecessary logging costs without sacrificing critical observability signals.

What it does

  • Audits Cloud Logging costs for a specific Google Cloud project.
  • Reconciles billing export data with volume metrics to ensure accurate cost attribution.
  • Identifies top logging contributors and cost drivers.
  • Generates a structured FinOps report with visual charts and actionable insights.
  • Provides concrete log sink exclusion filters to reduce extraneous spend.
  • Offers a 'Prove It' feature to verify cost claims against raw data sources.

When to use it

  • When you need to audit and understand your current Cloud Logging spend.
  • When you are looking for ways to reduce logging costs without losing critical data.
  • When you need to identify the noisiest log patterns or services.
  • When you need to generate a report for stakeholders regarding logging efficiency.

Advantages

  • Provides data-backed recommendations for cost reduction.
  • Offers clear, copy-pasteable exclusion filters for immediate implementation.
  • Distinguishes between invoiced costs and list-price estimates.
  • Maintains transparency by citing data sources and formulas for all cost claims.
  • Supports non-interactive, automated execution for scheduled audits.

Usage examples

“Audit the logging costs for my current project and tell me where I can save money.”
The agent will collect usage data, analyze cost drivers, and generate a report highlighting specific log streams and exclusion filters to reduce monthly spend.
“Why are my logging costs so high this month? Can you prove the numbers?”
The agent will provide a breakdown of top cost drivers and use the 'Prove It' feature to walk through the formulas and data sources behind the cost figures.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/google/cloud-logging-finops/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip cloud-logging-finops.zip -d .agents/skills

Documentation by Google

Cloud Logging Finops

Non-interactive runs. When no user can answer (e.g. a scheduled or automated run), ask nothing: audit the project named in the request, or the active gcloud project; use --billing-mode=search; cover all five report topics (Step 2.5); and never enable an API or upgrade a log bucket. Put anything that needed a user (a disabled API, a missing role, the upgrade advisory) in the report instead.

Usage Attribution

MUST READ: Before executing any gcloud, REST API, or MCP command, you MUST read and follow the instructions in Usage Attribution.

Step 0: Locate the Cloud Billing Export

The audit covers one Google Cloud project, {project_id}: the project the user names or, if they don't name one, the active gcloud project (gcloud config get project), confirmed with the user.

Discover everything else (log buckets, Observability Analytics, sinks, exclusions, metrics) yourself; never ask the user about those. The billing export is the exception: finding it unaided can mean scanning every project on the billing account, so ask once, before running anything, and don't start a search until the user has chosen answer 3 (single-select, using the host's question tool if it has one):

Do you know where the Cloud Billing export for {project_id} is?

  1. Yes — here it is (the BigQuery table ID project.dataset.table, or just the project and dataset)

  2. There's no billing export for this project

  3. No / not sure — search for it (seconds on a small project; on a large billing account it can take a long time)

AnswerFlagsCost figures
1--billing-mode=explicit plus --billing-table (or --billing-project/--billing-dataset)invoiced
2--billing-mode=nonelist-price estimates
3--billing-mode=search (default)invoiced if found, else estimates

Answer 3's search has no time limit: it checks {project_id} first (usually under 10 s, 1–2 min with many tables), then every project on its billing account (can take many minutes; progress prints every 30 s). Tell the user this before launching. If the wait is unacceptable, offer to switch to answer 1 (they look up the table) or answer 2 (skip the export and use list-price estimates). Don't suggest setting up an export to make the search faster.

If the search found an export, tell the user: "Next time, pass --billing-table=<table> and discovery drops to about two seconds."

Step 1: Environment Setup

Check these prerequisites before Step 2; fix only what is missing:

  • gcloud: if gcloud is not installed, follow https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt.

  • Project: run gcloud config get project; if it isn't {project_id} (from Step 0), run gcloud config set project {project_id}.

  • Credentials: the scripts use Application Default Credentials. Run gcloud auth application-default login, or set GOOGLE_APPLICATION_CREDENTIALS to a service account key.

  • Billing: the project must have an active billing account attached.

  • APIs: don't enable APIs up front; the Logging, Monitoring, BigQuery and Observability APIs are on by default in new projects. Only if the collector reports an API as disabled (SERVICE_DISABLED, "has not been used in project"), name it, ask the user, and on approval run gcloud services enable {api} --project={project_id} (tagged as described below):

    • logging, monitoring: required; without them there is nothing to audit.

    • bigquery: invoiced costs from the billing export.

    • observability: resolves the project's default log scope, so log samples match what Logs Explorer shows.

    • cloudasset, cloudbilling: only answer 3's search across the billing account.

IAM roles for the identity running the audit. The skill never grants roles: the scripts run with the user's own credentials and read only what those credentials can. When a step fails on permissions, its advisory names the step; tell the user which role below it needs:

RoleNeeded for
roles/logging.viewer, roles/monitoring.viewerEvery audit: log buckets, sinks, log samples, volume metrics
roles/bigquery.jobUser, roles/bigquery.dataViewer (on the export dataset)Invoiced costs from the billing export
roles/logging.viewAccessor on log views in other projectsReading samples through a default log scope that includes them
roles/cloudasset.viewer, roles/billing.viewer (billing account)--billing-mode=search across the billing account
roles/logging.configWriterOnly the optional Observability Analytics upgrade (Step 3B)
[ -f /tmp/finops_venv/bin/python ] || (uv venv /tmp/finops_venv && uv pip install -r scripts/requirements.txt --python /tmp/finops_venv/bin/python)

The bundled scripts tag their Google Cloud API requests. For commands you run yourself, follow Usage Attribution.

Step 2: Data Collection

Start the collector below as a background process (it takes from seconds to many minutes), then go to Step 2.5 while it runs:

/tmp/finops_venv/bin/python scripts/collect_logging_data.py \
  --project-id {project_id} --billing-mode={none|explicit|search}

Optional: --billing-project, --billing-dataset, --billing-table (e.g. billing-proj.ds.gcp_billing_export_v1_XXXX or a curated FinOps view).

Outputs: logging_usage_summary.json, monthly_details/, service_details/, and [FINOPS ADVISORY] lines (see Step 3). The collector's output ends with a [COLLECTION PROFILE] table of per-stage timings; if the run took longer than the times in Step 0, or the user asks why the audit took so long, read that table before guessing.

Step 2.5: Ask What the Report Is For

Always ask this while the collector runs (multi-select). If the user skips it, cover all five topics:

What should this report answer?

  • Where is the money going — attribution by service and stream

  • Is spend growing — trends and projection

  • What can I safely turn off — concrete savings actions

  • What are these logs actually saying — noisiest patterns and samples

  • Severity and audit-log posture

The user's choices decide which outputs you read in depth and what your summary leads with; they never change what the collector gathers:

InterestRead deeply
Attributionservice_details/*.json, daily_services
Growthmonthly_details/*.json, mom_patterns, cost_projection
Savings actionsreduction_actions, extraneous_spend
What logs sayseverity_summary.samples_by_service, granular_analytics.top_signatures (Observability Analytics only)
Severity / auditseverity_summary, withheld-rule reasons

Your narrative goes in insights/executive_summary.html (see Executive Summary Authoring). You don't write the savings actions: the generated report's Cost Optimizer tab lists them from reduction_actions.

[!CAUTION] Never edit assets/report_template.html.

Step 3: Follow the Advisories

A. Tell the User What the Cost Figures Are Based On

[!IMPORTANT] Unless figures are invoiced (billing_metadata.invoiced), tell the user in plain language where you looked, what you found, and what the numbers are based on. Keep internals (stage numbers, mode names, HTTP codes, "quota project", "Cloud Asset Inventory") in the log and billing_metadata.fallback_chain.

  • Answer 1, the location gave no costs (explicit_table or explicit_scope step not found): the collector never searches beyond what the user named. Tell them what was wrong, from the step's detail (no rows for this project, no export table there, or the query failed), that costs are list-price estimates, and offer to rerun with a corrected location or with answer 3.

  • Answer 2 (user_declared_no_export): "I didn't search — you told me there's no billing export — so costs are list-price estimates, not invoiced amounts." Never call a skipped search exhausted.

  • Answer 3, found nothing (billing_account status not_found): "I searched this project and your billing account and found no billing export. Costs are list-price estimates (quote each SKU's price and free tier from pricing.skus) over a trailing 30 days." Only this case supports recommending export setup. Cite the official pricing page (https://cloud.google.com/products/observability/pricing) as the source of list prices.

  • Answer 3, search failed on permissions (any step status inconclusive): tell the user the lookup couldn't complete, so costs are estimates. Never tell them no billing export exists; the search didn't finish.

  • Answer 3, this project's table rejected (local_project status no_project_records): "This project has a billing export, but it holds no records for this project, so I searched the rest of the billing account." Then report the outcome of that wider search as above.

  • Partial history: months are labelled actual_bq_billing or usage_estimated; state the exact date boundary in the executive summary.

When on list pricing, recommend export for accuracy: future audits would use the actual invoice, including discounts, over multiple months.

B. Observability Analytics

Observability Analytics was formerly called Log Analytics; the scripts' advisories and field names still use the old name.

  • Disabled: present the advisory, including that upgrading the log bucket is irreversible, then end your reply with a direct question, e.g. "Do you want me to upgrade the _Default log bucket to Observability Analytics? This can't be undone." Telling the user how to run it themselves is not asking. Only after they approve upgrading that log bucket, run /tmp/finops_venv/bin/python scripts/enable_log_analytics.py --project-id {project_id}. The audit proceeds on Cloud Monitoring either way.

[!CAUTION] Never run enable_log_analytics.py or gcloud logging buckets update --enable-analytics in the same turn you raise the advisory, or on general permission like "do whatever you need".

  • < 24 hours old: the 14-day Cloud Monitoring baseline is used until samples accumulate (~1–2 hours).

  • 1–13 days: cite the sample window in the report.

  • ≥ 14 days: full SQL analytics.

  • Representative logs unavailable advisory: samples are missing because your environment can't read log entries (needs roles/logging.viewer), not because streams are empty. Relay the error and role; per-stream detail is in severity_summary.sample_errors.

  • Samples empty but the stream has volume: samples are read through the project's default log scope, like Logs Explorer (analytics_metadata.log_read_scope). If its source is project and it has a note, the scope couldn't be resolved, so logs held outside this project's log buckets weren't read. Say that and relay the note; never say the stream has no logs.

C. Measurement Integrity

[!CAUTION] Never quote cost or volume derived from Observability Analytics payload byte sums; they overstate billed volume about 2x.

QuestionSource
Cost, GiB ingestedBilling export (billing.query_logging_billing_costs, daily_gib, monthly_costs)
Service mixlogging.googleapis.com/billing/bytes_ingested (resource_type)
Log stream / severity volumelogging.googleapis.com/byte_count (log, severity)
Severity mix, entry contentObservability Analytics SQL (constants.PAYLOAD_BYTES_SQL)
  • Totals come from the invoice when it exists; metrics only supply shares. Never put a metric-derived total next to an invoiced one.

  • byte_count (received) and billing/bytes_ingested (billed) differ by ~1.5x or more; never divide one by the other.

  • If telemetry_integrity.status is degraded, say dips on the listed days look like a metric defect that won't self-correct, and repeat the limits in telemetry_integrity.note. Never claim with certainty that nothing changed.

  • A month with is_partial: true is month-to-date. Label it so, and never call it a complete month or "last month".

D. Extraneous Spend

extraneous_spend.headline is a conservative floor: the sum of the reduction_actions.actions with counted: true (duplicate bucket routing, flow-log sampling, DEBUG logs, stale exclusions), each priced on exactly what its remedy removes. Everything else is surfaced, never counted: over-retention (not quantified), sampled exclusion rules (estimates), and Data Access audit logs (in withheld).

  1. Report it as a floor (≥ X%), never a point estimate or "up to".

  2. If status is insufficient_data, give no figure — not a guess, a benchmark, or $0.

  3. Quote any action's flag verbatim; it is written for the reader.

  4. Uncounted actions and uncounted_total_pct may be mentioned as upside, never added to the headline.

  5. If headline.exceeds_sanity_ceiling, say the headline isn't reliable, name the largest counted action, and flag it for manual review. Offer no number.

  6. If inventory_unavailable is non-empty, say log sink, exclusion and flow-log actions weren't checked; never say none exist.

  7. Whenever Data Access audit logs come up (a withheld entry, or the user names them), say they are left out of the number because they need a compliance decision: disabling or excluding them is frequently prohibited by compliance or security policy, so the owner must confirm before acting.

E. Exclusion Filters and Actions
  • Only Cost Optimizer actions carry filters and savings; Service Details volumes are not savings. Report sample_coverage.shown_pct.

  • Quote an action's monthly figures (monthly_gib, monthly_usd), never a rule's sample-window GiB (granular_analytics.exclusion_candidates).

  • rule_scope: stream drops every log entry of that severity in the stream; say so.

  • If refused_claims is non-empty, name the streams the safety gate removed.

Never offered as actions: CRITICAL/ALERT/EMERGENCY (incident signal), free _Required streams ($0, audit retention), Data Access audit logs (often compliance-mandated; report, never count), and streams with no measured volume.

[!CAUTION] Hand-written exclusion filters must: include a severity predicate (severity = "DEFAULT" for DEFAULT — omitting it matches everything); use the URL-encoded log ID (compute.googleapis.com%2Ffirewall); never embed unescaped log text or rotating tokens (UUIDs, IPs, long integers, times) in a regex; and respect the list above.

Step 4: Build and Deliver the Report

/tmp/finops_venv/bin/python scripts/build_report.py --summary logging_usage_summary.json --insights-dir insights/ --output log_usage_report.html

build_report.py writes an executive summary unless you provide insights/executive_summary.html.

Give the user one link that, when clicked, opens the fully rendered report — not raw HTML, not a missing file — from wherever the user actually is. Confirm that will happen before you post it.

Then list what they can explore (charts, service drilldowns, ranked actions with copyable filters, ✓ Prove It drawers) and suggest 3–4 follow-up questions drawn from this project's data, phrased to ask as-is.

If the user asked something specific, answer it directly with both GiB and USD, from monthly_aggregations (latest_complete_month names the newest whole month; each month's top_service is its Top Cost Driver), mom_patterns, cost_projection, trailing_30d_summary (its top_driver is the report's Top Cost Driver without an invoice), granular_analytics (present only when Observability Analytics ran), or the per-service/month detail files.

Step 5: Follow-Up Questions

Phase 1 (default): answer from the JSON on disk in a few sentences or a small table, name what the data can't settle, then stop and offer 3–4 ways to go deeper. Don't re-run collection or re-query sources.

Question aboutRead
A severityseverity_summary, granular_analytics.top_signatures for that severity
A serviceservice_details/{service}.json, top_signatures and top_log_names for it
An optimization actionits entry in reduction_actions.actions (claims, refused_claims, flag, counted)

Phase 2 (only after the user picks a direction): go as deep as it needs. Run Observability Analytics SQL against analytics_metadata.table_name, the _AllLogs view the collector measured. Step 3 still applies.

Step 6: Prove It

provenance.claims[<id>] records each headline figure's formula, sources (exact query, Google Cloud console link, steps; only the 10 largest streams per action), known differences from the console, and runnable checks (covering every stream). Ids include latest_complete_spend, mtd_run_rate, trailing_30d_volume, estimated_run_rate, top_cost_driver, extraneous_spend, severity_costs, service_mix, action::<action id>. A claim built from others lists them in see_also (extraneous_spend → its counted actions); prove those too, and verify_claim.py re-checks them with it.

When asked to prove a figure:

  1. Now, from disk: walk the formula with its inputs; list each source with its Google Cloud console link, its query exactly as recorded, and steps; then the differences.

  2. Same turn, in the background: run /tmp/finops_venv/bin/python scripts/verify_claim.py --summary <summary> --claim "<id>"; don't wait.

  3. When it finishes: a table (check | report | live | Δ | ✓/△/✗) and a one-line verdict. Explain △ with the recorded differences; give ✗ causes in one line each.

[!CAUTION] Prove It is the only request that may re-query sources, and only via verify_claim.py. Don't re-run collection or alter the recorded queries.

Disclose when relevant: whether the claim was priced (pricing.mode) per_sku (each SKU's price and free tier in pricing.skus) or blended (reason in pricing.notes); that service and severity figures exclude credits; and, if cross_project_billing, that reproducing it needs roles/bigquery.dataViewer on the billing export dataset and roles/bigquery.jobUser.

Files

scripts/collect_logging_data.py

"""Collects GCP logging volume and cost data.

Sources: Cloud Monitoring, Log Analytics, and the BigQuery billing export.
"""

import collections
from collections.abc import Sequence
import concurrent.futures
import datetime
import os
from typing import Any, Dict, List, Optional

from absl import app
from absl import flags
from actions import merge_actions
from aggregations import get_daily_services
from aggregations import get_mom_patterns
from aggregations import get_monthly_aggregations
from aggregations import get_severity_summary
from aggregations import get_trailing_30d_summary
from aggregations import get_weekly_aggregations
from aggregations import invoiced_window_gib
from aggregations import latest_complete_month
from aggregations import merge_data
from aggregations import project_month
from aggregations import top_driver
from aggregations import window_sums
from analytics import detect_log_analytics_buckets
from analytics import fetch_logging_api_samples
from analytics import probe_log_analytics_data
from analytics import query_log_analytics_breakdown
import attribution
import billing
from billing import resolve_billing_source
from constants import DEFAULT_ANALYSIS_MONTHS
from constants import DEFAULT_LOCATION
from constants import DEFAULT_SAMPLE_DAYS
from constants import DEFAULT_TELEMETRY_LOOKBACK_DAYS
from constants import MONITORING_RETENTION_DAYS
from constants import write_json
from exclusion_rules import generate_exclusion_candidates
from google.cloud import bigquery
from google.cloud import logging_v2
from google.cloud import monitoring_v3
from google.cloud.logging_v2.services import config_service_v2
from inventory import authed_session
from inventory import fetch_flow_log_configs
from inventory import fetch_log_router_inventory
from inventory import resolve_log_read_scope
from monitoring import get_query_interval
from monitoring import parse_billing_results
from monitoring import parse_severity_results
from monitoring import parse_stream_results
from monitoring import query_log_volume
from monitoring import query_severity_volume
from monitoring import query_stream_volume
from output import print_advisory
from output import write_monthly_details
from output import write_service_details
import perf
from pricing import build_price_book
from provenance import build_provenance
import telemetry_integrity
from waste import compute_extraneous_spend

ConfigServiceV2Client = config_service_v2.ConfigServiceV2Client

FLAGS = flags.FLAGS
if "project-id" not in FLAGS:
  flags.DEFINE_string("project-id", None, "GCP Project ID to query.")
if "output" not in FLAGS:
  flags.DEFINE_string(
      "output",
      "logging_usage_summary.json",
      "Output JSON file path for summary index.",
  )
if "billing-project" not in FLAGS:
  flags.DEFINE_string(
      "billing-project",
      None,
      "Optional GCP Project ID where BigQuery billing export resides.",
  )
if "billing-dataset" not in FLAGS:
  flags.DEFINE_string(
      "billing-dataset",
      None,
      "Optional BigQuery dataset containing billing export tables.",
  )
if "billing-table" not in FLAGS:
  flags.DEFINE_string(
      "billing-table",
      None,
      "Optional explicit BigQuery billing export table name (e.g."
      " `proj.ds.gcp_billing_export_v1_XXXX`).",
  )
if "billing-mode" not in FLAGS:
  flags.DEFINE_enum(
      "billing-mode",
      billing.MODE_SEARCH,
      list(billing.BILLING_MODES),
      "What is already known about where the Cloud Billing BigQuery export"
      " lives. 'explicit' probes only what --billing-table/-project/-dataset"
      " names (~2s, invoiced costs); 'none' skips discovery entirely because"
      " the caller has confirmed there is no export (instant, estimated"
      " costs); 'search' (default) looks for it -- this project first, then"
      " every project on the billing account.",
  )


def collect_data(
    monitoring_client: monitoring_v3.MetricServiceClient,
    project_id: str,
    output_path: str,
    now: datetime.datetime,
    config_client: Optional[ConfigServiceV2Client] = None,
    bq_client: Optional[bigquery.Client] = None,
    sample_days: int = DEFAULT_SAMPLE_DAYS,
    location: str = DEFAULT_LOCATION,
    billing_project: Optional[str] = None,
    billing_dataset: Optional[str] = None,
    billing_table: Optional[str] = None,
    analysis_months: int = DEFAULT_ANALYSIS_MONTHS,
    logging_client: Optional[Any] = None,
    billing_mode: str = billing.MODE_SEARCH,
    http_session: Optional[Any] = None,
) -> Dict[str, Any]:
  """Collects all sources, writes the summary JSON, and returns it."""
  timer = perf.StageTimer()
  client_info = attribution.client_info(attribution.COLLECT_LOGGING_DATA)
  if config_client is None:
    config_client = ConfigServiceV2Client(client_info=client_info)
  if bq_client is None:
    bq_client = bigquery.Client(project=project_id, client_info=client_info)
  if logging_client is None:
    logging_client = logging_v2.Client(
        project=project_id, client_info=client_info
    )
  # Inventory checks that could not run are disclosed, never read as "none".
  inventory_unavailable: List[str] = []
  if http_session is None:
    try:
      http_session = authed_session()
    except Exception as e:  # pylint: disable=broad-except
      print(f"Notice: unable to build an authorized session: {e}")
      inventory_unavailable.append(f"authorized session: {e}")

  def _run_pillar_analytics():
    with timer.stage("log_analytics_buckets"):
      detected_buckets = detect_log_analytics_buckets(
          config_client, project_id, location
      )
    analytics_enabled_buckets = [
        b for b in detected_buckets if b["analytics_enabled"]
    ]
    is_analytics_enabled = len(analytics_enabled_buckets) > 0

    probe_info = {
        "status": "disabled",
        "days_available": 0.0,
        "table_name": None,
    }
    granular_raw = None
    if is_analytics_enabled:
      active = analytics_enabled_buckets[0]
      active_loc = active["location"]
      with timer.stage("log_analytics_probe"):
        probe_info = probe_log_analytics_data(
            bq_client,
            project_id,
            location=active_loc,
            bucket_id=active["bucket_id"],
            sample_days=sample_days,
            now=now,
            linked_dataset=active["linked_dataset"],
        )
      if probe_info["status"] in ("partial_window", "mature"):
        with timer.stage("log_analytics_breakdown"):
          granular_raw = query_log_analytics_breakdown(
              bq_client,
              probe_info["table_name"],
              sample_days=sample_days,
              location=active_loc,
          )
    return detected_buckets, is_analytics_enabled, probe_info, granular_raw

  def _run_pillar_billing():
    return resolve_billing_source(
        bq_client=bq_client,
        project_id=project_id,
        override_table=billing_table,
        billing_project=billing_project,
        billing_dataset=billing_dataset,
        analysis_months=analysis_months,
        now=now,
        billing_mode=billing_mode,
    )

  def _run_billing_chain():
    """Resolves billing, then the billed-volume series whose window needs it."""
    with timer.stage("billing_discovery"):
      billing_result = _run_pillar_billing()
    lookback = (
        MONITORING_RETENTION_DAYS
        if billing_result.invoiced
        else DEFAULT_TELEMETRY_LOOKBACK_DAYS
    )
    with timer.stage("gcm_billed_bytes"):
      results = query_log_volume(
          monitoring_client, project_id, get_query_interval(now, lookback)
      )
    return billing_result, parse_billing_results(results)

  def _run_stream_volume():
    """Fetches `byte_count` once for all consumers."""
    with timer.stage("gcm_byte_count_streams"):
      return query_stream_volume(
          monitoring_client,
          project_id,
          now=now,
          days=int(max(sample_days, DEFAULT_TELEMETRY_LOOKBACK_DAYS)),
      )

  def _run_router_inventory():
    if http_session is None:
      return {"sinks": [], "exclusions": []}, []
    with timer.stage("log_router_inventory"):
      return fetch_log_router_inventory(http_session, project_id)

  def _run_flow_log_configs():
    if http_session is None:
      return [], []
    with timer.stage("flow_log_configs"):
      return fetch_flow_log_configs(http_session, project_id)

  def _run_log_read_scope():
    with timer.stage("log_read_scope"):
      return resolve_log_read_scope(http_session, project_id)

  # These groups are independent, so they run concurrently.
  with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
    fut_analytics = executor.submit(_run_pillar_analytics)
    fut_billing = executor.submit(_run_billing_chain)
    fut_streams = executor.submit(_run_stream_volume)
    fut_router = executor.submit(_run_router_inventory)
    fut_flow_logs = executor.submit(_run_flow_log_configs)
    fut_read_scope = executor.submit(_run_log_read_scope)

    detected_buckets, is_analytics_enabled, probe_info, granular_raw = (
        fut_analytics.result()
    )
    billing_result, parsed_billing = fut_billing.result()
    stream_series = fut_streams.result()
    router_inventory, router_unavailable = fut_router.result()
    flow_log_configs, flow_unavailable = fut_flow_logs.result()
    read_scope = fut_read_scope.result()
  inventory_unavailable += router_unavailable + flow_unavailable

  parsed_streams = parse_stream_results(stream_series.series)
  if stream_series.missing_windows:
    print(
        "Notice: byte_count is incomplete for"
        f" {len(stream_series.missing_windows)} window(s):"
        f" {', '.join(stream_series.missing_windows)}"
    )

  # `billing/bytes_ingested` can silently under-report billed volume. Suspect
  # days are disclosed, never dropped (it is the only per-service split). The
  # invoice is the control when present; else `byte_count` (relative only).
  billed_daily = telemetry_integrity.daily_totals(parsed_billing)
  billing_costs = billing_result.costs or {}
  invoiced_daily_gib = billing_costs.get("daily_gib")
  if invoiced_daily_gib:
    telemetry_verdict = telemetry_integrity.assess_against_invoice(
        billed_daily=billed_daily,
        invoiced_daily_gib=invoiced_daily_gib,
        now=now,
    )
  else:
    # Summing the per-stream series equals the ungrouped daily total.
    telemetry_verdict = telemetry_integrity.assess(
        billed_daily=billed_daily,
        received_daily=telemetry_integrity.daily_totals(parsed_streams),
    )
  if telemetry_verdict["compromised_days"]:
    print(
        "[TELEMETRY INTEGRITY]"
        f" {len(telemetry_verdict['compromised_days'])} day(s) of"
        " billed-volume telemetry under-report the volume that was billed:"
        f" {', '.join(telemetry_verdict['compromised_days'])}"
    )

  billed_by_service = window_sums(parsed_billing, now, sample_days)
  top_services = sorted(
      billed_by_service, key=billed_by_service.get, reverse=True
  )[:5]
  analytics_status = probe_info["status"]
  granular_analytics: Optional[Dict[str, Any]] = None
  severity_missing: List[str] = []

  if analytics_status == "mature":
    parsed_severity = granular_raw["severity_history"]
  else:
    with timer.stage("gcm_severity_volume"):
      severity_series = query_severity_volume(
          monitoring_client, project_id, top_services, now, days=sample_days
      )
    severity_missing = severity_series.missing_windows
    parsed_severity = parse_severity_results(severity_series.series)

  # Extract SQL samples if available, then fetch missing via Logging API
  samples_by_service: Dict[str, Dict[str, List[Dict[str, Any]]]] = (
      collections.defaultdict(lambda: collections.defaultdict(list))
  )
  if granular_raw is not None:
    for srv_name, sevs in granular_raw["samples_by_service"].items():
      for sev_name, items in sevs.items():
        samples_by_service[srv_name][sev_name].extend(items)

  with timer.stage("logging_api_samples"):
    sample_errors = fetch_logging_api_samples(
        logging_client=logging_client,
        project_id=project_id,
        top_services=top_services,
        parsed_severity=parsed_severity,
        samples_by_service=samples_by_service,
        now=now,
        lookback_days=sample_days,
        read_scope=read_scope,
    )
  samples_dict = {srv: dict(sevs) for srv, sevs in samples_by_service.items()}

  merged_data = merge_data(parsed_billing, parsed_severity)
  base_dir = os.path.dirname(os.path.abspath(output_path))
  write_monthly_details(
      parsed_billing, os.path.join(base_dir, "monthly_details"), project_id
  )
  write_service_details(
      merged_data,
      os.path.join(base_dir, "service_details"),
      project_id,
      samples_by_service=samples_dict,
  )

  # The invoice sets the run rate; the metric supplies the service split.
  trailing_30d = get_trailing_30d_summary(
      parsed_billing=parsed_billing,
      now=now,
      invoiced_daily_gib=billing_costs.get("daily_gib"),
  )
  monthly_run_rate_gib = trailing_30d["monthly_run_rate_gib"]

  # Every dollar in the summary is priced from this book: per SKU, with the
  # 50 GiB free tier on Log Storage only.
  stream_sums = window_sums(parsed_streams, now, sample_days)
  price_book = build_price_book(
      baseline_gib=monthly_run_rate_gib,
      now=now,
      window_start=trailing_30d["window_start"],
      monthly_costs=billing_costs.get("monthly_costs"),
      daily_gib_by_sku=billing_costs.get("daily_gib_by_sku"),
      bytes_by_stream=stream_sums,
  )
  trailing_30d["projected_monthly_cost_usd"] = price_book.baseline_cost
  trailing_30d["projected_annual_cost_usd"] = round(
      price_book.baseline_cost * 12.0, 2
  )
  # Price each service on its window GiB scaled to the monthly run rate.
  window_gib = trailing_30d["total_gib"]
  to_monthly = monthly_run_rate_gib / window_gib if window_gib > 0 else 0.0
  for entry in trailing_30d["top_services"]:
    if not entry.get("is_remainder"):
      entry["cost_usd"] = price_book.service_cost(
          entry["service"], entry["gib"] * to_monthly
      )
  trailing_30d["top_driver"] = top_driver(trailing_30d["top_services"])

  monthly_aggs = get_monthly_aggregations(
      billing_data=parsed_billing,
      price_book=price_book,
      billing_costs=billing_costs,
      now=now,
  )
  invoiced_months = sorted(
      m
      for m, entry in monthly_aggs.items()
      if entry["data_source"] == "actual_bq_billing"
  )
  # Named from the months actually retrieved, not the months requested.
  reporting_mode = (
      f"billing_invoiced_{len(invoiced_months)}mo"
      if invoiced_months
      else "telemetry_trailing_30d"
  )

  weekly_aggs = get_weekly_aggregations(
      parsed_billing=parsed_billing, now=now, price_book=price_book
  )
  mom_trends = get_mom_patterns(monthly_aggs)
  cost_projection = project_month(
      now=now,
      price_book=price_book,
      parsed_billing=parsed_billing,
      invoiced_daily_gib_by_sku=billing_costs.get("daily_gib_by_sku"),
  )

  # Present only when the Log Analytics breakdown ran.
  if granular_raw is not None:
    granular_analytics = {
        "sample_period_days": probe_info["days_available"],
        "sample_start": probe_info["earliest_log"],
        "sample_end": probe_info["latest_log"],
        "top_log_names": granular_raw["top_log_names"],
        "top_signatures": granular_raw["top_signatures"],
        # Gross run rate: the book subtracts the free tier itself.
        "exclusion_candidates": generate_exclusion_candidates(
            granular_raw["top_signatures"],
            price_book,
            project_id=project_id,
            total_entries=probe_info["total_entries"],
            total_sample_bytes=granular_raw["total_payload_bytes"],
            monthly_run_rate_gib=monthly_run_rate_gib,
            sample_days=probe_info["days_available"],
        ),
    }

  severity_summary = get_severity_summary(
      parsed_severity,
      now,
      days=sample_days,
      samples_by_service=samples_dict,
      severity_source=(
          "log_analytics"
          if analytics_status == "mature"
          else "cloud_monitoring"
      ),
  )
  # Without this, a truncated fetch looks like a real drop in ERROR volume.
  severity_summary["missing_windows"] = severity_missing
  severity_summary["sample_errors"] = sample_errors

  daily_services = get_daily_services(parsed_billing, now, days=sample_days)

  # Uses Cloud Monitoring volume and router/flow-log inventory, never payload
  # byte sums (which overstate billed volume).
  extraneous_spend, lever_actions = compute_extraneous_spend(
      billed_by_service=billed_by_service,
      byte_count_by_stream=stream_sums,
      window_days=float(sample_days),
      monthly_gib=monthly_run_rate_gib,
      price_book=price_book,
      project_id=project_id,
      sinks=router_inventory["sinks"],
      exclusions=router_inventory["exclusions"],
      buckets=detected_buckets,
      flow_log_configs=flow_log_configs,
      # Invoiced basis, matching the run rate it is divided by.
      billed_window_gib=invoiced_window_gib(
          billing_costs.get("daily_gib"),
          now,
          float(sample_days),
      ),
  )
  extraneous_spend["inventory_unavailable"] = inventory_unavailable

  # Merges levers and exclusion rules on the same stream into one action.
  reduction_actions = merge_actions(
      lever_actions,
      granular_analytics["exclusion_candidates"] if granular_analytics else [],
      price_book,
  )

  index_content = {
      "project_id": project_id,
      "last_updated": now.isoformat(),
      "reporting_mode": reporting_mode,
      "trailing_30d_summary": trailing_30d,
      # How every dollar was priced; read by the report and Prove It.
      "pricing": price_book.to_dict(),
      "weekly_aggregations": weekly_aggs,
      "analytics_metadata": {
          "enabled": is_analytics_enabled,
          "status": analytics_status,
          "days_available": probe_info["days_available"],
          # The `_AllLogs` view the breakdown measured; Prove It queries it.
          "table_name": probe_info["table_name"],
          "buckets": detected_buckets,
          # Where Logging API samples were read; explains empty samples.
          "log_read_scope": read_scope,
      },
      "billing_metadata": billing_result.summary(),
      "monthly_aggregations": monthly_aggs,
      "latest_complete_month": latest_complete_month(monthly_aggs),
      "mom_patterns": mom_trends,
      "cost_projection": cost_projection,
      "severity_summary": severity_summary,
      "daily_services": daily_services,
      "extraneous_spend": extraneous_spend,
      "reduction_actions": reduction_actions,
      "telemetry_integrity": telemetry_verdict,
      # Per-stage timings.
      "collection_profile": timer.profile(),
  }

  if granular_analytics is not None:
    index_content["granular_analytics"] = granular_analytics

  # Built last from the finished summary; source of truth for "Prove It" and
  # `verify_claim.py`.
  index_content["provenance"] = build_provenance(index_content)

  write_json(output_path, index_content)
  print(timer.render())

  print_advisory(index_content, output_path)

  return index_content


def main(argv: Sequence[str]) -> None:
  if len(argv) > 1:
    raise app.UsageError("Too many command-line arguments.")
  project_id = FLAGS["project-id"].value
  if not project_id:
    raise app.UsageError("Flag --project-id is required.")
  if FLAGS["billing-mode"].value == billing.MODE_EXPLICIT and not (
      FLAGS["billing-table"].value
      or FLAGS["billing-project"].value
      or FLAGS["billing-dataset"].value
  ):
    raise app.UsageError(
        "--billing-mode=explicit needs --billing-table, --billing-project or"
        " --billing-dataset."
    )

  # Optional clients are built by `collect_data`.
  collect_data(
      monitoring_client=monitoring_v3.MetricServiceClient(
          client_info=attribution.client_info(attribution.COLLECT_LOGGING_DATA)
      ),
      project_id=project_id,
      output_path=FLAGS["output"].value,
      now=datetime.datetime.now(datetime.timezone.utc),
      billing_project=FLAGS["billing-project"].value,
      billing_dataset=FLAGS["billing-dataset"].value,
      billing_table=FLAGS["billing-table"].value,
      billing_mode=FLAGS["billing-mode"].value,
  )


if __name__ == "__main__":
  app.run(main)

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/cloud-logging-finops · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cloud-logging-finops.zip