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/waste.py

"""Extraneous log spend model for Cloud Logging FinOps.

Computes a conservative floor for recoverable spend from billing/bytes_ingested
and byte_count only; Log Analytics payload bytes overstate billed volume ~2x.
Each lever is emitted as an `actions.Action`; the headline is the sum of the
counted ones, priced on exactly the claims their remedy can act on.
"""

import re
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple

from actions import Action
from actions import ALL_SEVERITIES
from actions import Claim
from actions import filter_from_claims
from actions import SOURCE_LEVER
from constants import billable_gib
from constants import BYTES_PER_GIB
from constants import FLOW_LOG_TARGET_SAMPLING
from constants import IMMUTABLE_RETENTION_BUCKETS
from constants import INCLUDED_RETENTION_DAYS
from constants import WASTE_SANITY_CEILING_PCT
from exclusion_rules import decode_log_id
from exclusion_rules import is_data_access
from exclusion_rules import is_free_required
import messages
from pricing import PriceBook

# Matches LOG_ID("...") / logName tokens inside a Log Router filter.
_LOG_ID_RE = re.compile(r'LOG_ID\(\s*"([^"]+)"\s*\)', re.IGNORECASE)
_LOG_NAME_RE = re.compile(r'logs/([^"\s$]+)', re.IGNORECASE)

# Max share a "dead" exclusion target may still carry (tolerates stragglers).
_DEAD_RULE_MAX_SHARE = 0.02

# Removing one of two destinations recovers half the billed bytes (a floor).
_DUPLICATE_COPY_FRACTION = 0.5

# Unfiltered sinks pair up combinatorially; evidence shows a sample plus count.
_MAX_EVIDENCE_PAIRS = 8

_LOG_ID_TERM = r'LOG_ID\(\s*"[^"]+"\s*\)'
# A sink filter of `NOT LOG_ID(...)` terms joined by AND, the shape of the stock
# `_Default` sink filter: "every stream but these".
_EXCLUSION_ONLY_FILTER_RE = re.compile(
    rf"^\s*NOT\s+{_LOG_ID_TERM}(\s+AND\s+NOT\s+{_LOG_ID_TERM})*\s*$",
    re.IGNORECASE,
)
# A sink exclusion of `LOG_ID(...)` terms joined by OR: drops whole streams.
_WHOLE_STREAM_EXCLUSION_RE = re.compile(
    rf"^\s*{_LOG_ID_TERM}(\s+OR\s+{_LOG_ID_TERM})*\s*$", re.IGNORECASE
)


class _ClaimLedger:
  """Prevents two levers from counting the same bytes twice.

  Each stream can be claimed at most once in total. `retain` records that only
  part of a stream stays billed (e.g. after dedup), scaling later claims.
  """

  def __init__(self) -> None:
    self._claimed: Dict[str, float] = {}
    self._retained: Dict[str, float] = {}

  def retain(self, key: str, factor: float) -> None:
    """Records that only `factor` of `key`'s bytes stay billed hereafter."""
    self._retained[key] = self.retained(key) * max(0.0, min(1.0, factor))

  def retained(self, key: str) -> float:
    return self._retained.get(key, 1.0)

  def claim(self, key: str, fraction: float) -> float:
    """Claims up to `fraction` of `key`'s billed rest; returns the share won."""
    # The returned share is relative to all of `key`'s bytes.
    fraction = max(0.0, min(1.0, fraction)) * self.retained(key)
    already = self._claimed.get(key, 0.0)
    granted = max(0.0, min(fraction, 1.0 - already))
    if granted > 0:
      self._claimed[key] = already + granted
    return granted


def _log_ids_in_filter(filter_expr: str) -> List[str]:
  """Extracts referenced log IDs, decoded, from a Log Router filter."""
  found = _LOG_ID_RE.findall(filter_expr or "")
  found += _LOG_NAME_RE.findall(filter_expr or "")
  return [decode_log_id(f).rstrip("$") for f in found]


def _stream_suffix(log_id: str) -> str:
  """Returns the service-independent suffix of a log ID."""
  # `compute.googleapis.com/vpc_flows` and
  # `networkmanagement.googleapis.com/vpc_flows` share the suffix `vpc_flows`,
  # which identifies a migrated stream as the successor of an excluded one.
  return log_id.rsplit("/", 1)[-1].lower()


def _sink_streams(
    sink: Dict[str, Any], log_ids: Set[str]
) -> Optional[Set[str]]:
  """Returns the log IDs a bucket sink provably stores, or None if unknown."""
  # Only empty filters and conjunctions of `NOT LOG_ID(...)` are evaluated, and
  # only whole-stream `LOG_ID(...)` exclusions are subtracted.
  expr = (sink.get("filter") or "").strip()
  if not expr:
    routed = set(log_ids)
  elif _EXCLUSION_ONLY_FILTER_RE.match(expr):
    routed = log_ids - set(_log_ids_in_filter(expr))
  else:
    return None
  for exclusion in sink.get("exclusions") or ():
    if exclusion.get("disabled"):
      continue
    excluded = (exclusion.get("filter") or "").strip()
    if not _WHOLE_STREAM_EXCLUSION_RE.match(excluded):
      return None
    routed -= set(_log_ids_in_filter(excluded))
  return routed


def _duplicate_pairs(
    sinks: Sequence[Dict[str, Any]], log_ids: Set[str]
) -> List[Tuple[str, str, Set[str]]]:
  """Returns `(a, b, overlap)` for bucket-sink pairs billing streams twice."""
  # Ingestion is billed per destination bucket. Only pairs whose overlap is
  # provable and non-empty are returned.
  routed = []
  for sink in sinks:
    if (
        "logging.googleapis.com" not in str(sink.get("destination", ""))
        or sink.get("name") == "_Required"
        or sink.get("disabled")
    ):
      continue
    streams = _sink_streams(sink, log_ids)
    if streams:
      routed.append((str(sink.get("name")), streams))
  pairs = []
  for i, (first, first_streams) in enumerate(routed):
    for second, second_streams in routed[i + 1 :]:
      overlap = first_streams & second_streams
      if overlap:
        pairs.append((first, second, overlap))
  return pairs


def _format_pairs(pairs: Sequence[Tuple[str, str, Set[str]]]) -> str:
  """Renders sink pairs for evidence prose, bounded to a readable sample."""
  shown = ", ".join(f"{a} + {b}" for a, b, _ in pairs[:_MAX_EVIDENCE_PAIRS])
  remainder = len(pairs) - _MAX_EVIDENCE_PAIRS
  if remainder > 0:
    return f"{shown}, and {remainder} more pair(s)"
  return shown


def compute_extraneous_spend(
    billed_by_service: Dict[str, float],
    byte_count_by_stream: Dict[Tuple[str, str], float],
    window_days: float,
    monthly_gib: float,
    price_book: PriceBook,
    project_id: str,
    sinks: Optional[Sequence[Dict[str, Any]]] = None,
    exclusions: Optional[Sequence[Dict[str, Any]]] = None,
    buckets: Optional[Sequence[Dict[str, Any]]] = None,
    flow_log_configs: Optional[Sequence[Dict[str, Any]]] = None,
    billed_window_gib: Optional[float] = None,
) -> Tuple[Dict[str, Any], List[Action]]:
  """Computes the conservative extraneous-spend floor and its lever actions.

  Args:
    billed_by_service: bytes from billing/bytes_ingested keyed by resource type,
      over the sample window.
    byte_count_by_stream: bytes from byte_count keyed by (log_id, severity).
    window_days: length of the measurement window in days.
    monthly_gib: gross monthly ingestion run-rate used as the baseline.
    price_book: per-SKU prices and baselines every saving is priced from.
    project_id: project the exclusion filters target.
    sinks: Log Router sinks.
    exclusions: project-level exclusions.
    buckets: log buckets with retention metadata.
    flow_log_configs: VPC flow log configs from the Compute / Network Management
      APIs.
    billed_window_gib: invoiced ingestion over the same window; preferred
      calibration anchor so numerator and (invoiced) denominator share a basis.

  Returns:
    `(extraneous_spend, lever_actions)`: the report contract, and the actions
    to pass to `actions.merge_actions`.
  """
  billable_monthly_gib = billable_gib(monthly_gib)
  if not byte_count_by_stream or billable_monthly_gib <= 0:
    return {
        "status": "insufficient_data",
        "reason": (
            "Authoritative volume metrics unavailable; refusing to estimate."
        ),
    }, []

  # Decoded once here so every comparison below is on plain IDs. Always-free
  # _Required streams are left out of every calculation.
  billable_streams: Dict[Tuple[str, str], float] = {}
  for (log_id, severity), num_bytes in byte_count_by_stream.items():
    key = (decode_log_id(log_id), severity)
    if not is_free_required(key[0]):
      billable_streams[key] = billable_streams.get(key, 0.0) + num_bytes

  # byte_count (received, carries log/severity labels) exceeds billed bytes by
  # ~1.5x, so rescale it onto the billed basis. Prefer the invoice as anchor.
  raw_stream_total = sum(billable_streams.values()) or 1.0
  if billed_window_gib is not None and billed_window_gib > 0:
    billed_total = billed_window_gib * BYTES_PER_GIB
  else:
    billed_total = sum(billed_by_service.values()) if billed_by_service else 0.0
  # Only ever scale down: if billed exceeds byte_count the labels are
  # incomplete, and inflating measured bytes would invent savings.
  calibration = min(
      billed_total / raw_stream_total if billed_total > 0 else 1.0, 1.0
  )
  billable_streams = {k: v * calibration for k, v in billable_streams.items()}
  total_stream_bytes = sum(billable_streams.values()) or 1.0

  bytes_by_log: Dict[str, float] = {}
  for (log_id, _), num_bytes in billable_streams.items():
    bytes_by_log[log_id] = bytes_by_log.get(log_id, 0.0) + num_bytes

  days = window_days if window_days > 0 else 1.0

  def monthly(num_bytes: float) -> float:
    return num_bytes / days * 30.0 / BYTES_PER_GIB

  def measured(log_id: str, severity: str) -> float:
    if severity == ALL_SEVERITIES:
      return bytes_by_log[log_id]
    return billable_streams[(log_id, severity)]

  ledger = _ClaimLedger()
  levers: List[Action] = []

  def add(
      lever_id: str,
      title: str,
      evidence: str,
      claims: Sequence[Tuple[str, str, float]] = (),
      manual_step: str = "",
      withheld: str = "",
      counted: bool = True,
      **kwargs: Any,
  ) -> None:
    """Prices one lever on the claims its remedy can act on."""
    # `claims` are `(log_id, severity|"*", window_bytes)`. A lever without a
    # manual step is remedied by an exclusion filter, so its claims pass the
    # same safety gate as every exclusion before anything is priced.
    claimed = [Claim(l, s, monthly(b)) for l, s, b in claims if b > 0]
    action = Action(
        id=lever_id,
        title=title,
        source=SOURCE_LEVER,
        evidence=evidence,
        manual_step=manual_step,
        withheld=withheld,
        **kwargs,
    )
    if manual_step or withheld:
      action.claims = claimed
    else:
      action.filter, action.claims, action.refused_claims = filter_from_claims(
          claimed, project_id
      )
      if not action.claims:
        action.withheld = messages.WITHHELD_NO_REMEDY
    gib = sum(c.monthly_gib for c in action.claims)
    action.counted = counted and gib > 0 and not action.withheld
    if gib > 0:
      gib_by_sku = price_book.split_by_logs(
          gib, ((c.log_id, c.monthly_gib) for c in action.claims)
      )
      action.monthly_gib = round(gib, 2)
      action.monthly_usd = price_book.saving(gib_by_sku)
      # Share of spend, not of volume: SKUs are priced differently.
      action.pct_of_billable = price_book.pct_of_spend(action.monthly_usd)
      action.gib_by_sku = {k: round(v, 2) for k, v in gib_by_sku.items() if v}
      # Prove It re-measures whole streams and scales by this share.
      stream_gib = sum(
          monthly(measured(c.log_id, c.severity)) for c in action.claims
      )
      action.stream_fraction = round(gib / stream_gib, 4)
    levers.append(action)

  # --- Duplicate bucket routing (billing mechanics) --------------------------
  dup_pairs = _duplicate_pairs(sinks or (), set(bytes_by_log))
  if dup_pairs:
    # Calibrated stream bytes include every copy; claim half (floor) of the
    # streams some pair provably routes twice.
    dup_claims = []
    for log_id in sorted(set().union(*(o for _, _, o in dup_pairs))):
      granted = ledger.claim(log_id, _DUPLICATE_COPY_FRACTION)
      ledger.retain(log_id, 1.0 - _DUPLICATE_COPY_FRACTION)
      dup_claims.append(
          (log_id, ALL_SEVERITIES, bytes_by_log[log_id] * granted)
      )
    add(
        "duplicate_bucket_routing",
        "Duplicate log bucket routing",
        "Sink pairs route the same streams to separate log buckets, and GCP"
        " bills ingestion once per destination bucket: "
        + _format_pairs(dup_pairs),
        dup_claims,
        manual_step=(
            "Add an exclusion to the redundant sink so each entry is billed to"
            " one destination bucket (google_logging_project_sink.exclusions)."
        ),
    )

  # --- Retention beyond the included 30 days (not measurable here) -----------
  over_retention = [
      b
      for b in buckets or ()
      if b["retention_days"] > INCLUDED_RETENTION_DAYS
      and b["bucket_id"] not in IMMUTABLE_RETENTION_BUCKETS
  ]
  if over_retention:
    add(
        "over_retention",
        "Buckets retaining logs beyond the included 30 days",
        "Buckets exceed the 30 days of retention included with ingestion: "
        + ", ".join(
            f"{b['bucket_id']} ({b['retention_days']}d)" for b in over_retention
        )
        + ". Per-bucket stored volume is not exposed by the metrics used"
        " here, so no savings are claimed.",
        manual_step=(
            "Reduce bucket retention to the 30 days included with ingestion"
            " (google_logging_project_bucket_config.retention_days)."
        ),
        counted=False,
        flag=messages.FLAG_NOT_QUANTIFIED,
    )

  # --- Stale exclusion: the rule's target stream moved -----------------------
  for exclusion in exclusions or ():
    if exclusion.get("disabled"):
      continue
    name = str(exclusion.get("name") or "exclusion")
    for log_id in _log_ids_in_filter(str(exclusion.get("filter") or "")):
      target_bytes = bytes_by_log.get(log_id, 0.0)
      if target_bytes / total_stream_bytes > _DEAD_RULE_MAX_SHARE:
        continue  # Rule is still doing its job.

      # Dead rule: a successor stream with the same suffix is the target.
      successors = {
          other: other_bytes
          for other, other_bytes in bytes_by_log.items()
          if other != log_id
          and not is_data_access(other)
          and _stream_suffix(other) == _stream_suffix(log_id)
          and other_bytes / total_stream_bytes > _DEAD_RULE_MAX_SHARE
      }
      stale_claims = [
          (other, ALL_SEVERITIES, other_bytes * ledger.claim(other, 1.0))
          for other, other_bytes in successors.items()
      ]
      if not any(b > 0 for _, _, b in stale_claims):
        continue
      add(
          f"stale_exclusion_intent::{_stream_suffix(log_id)}",
          f"Exclusion '{name}' no longer matches its target stream",
          f"Exclusion '{name}' targets LOG_ID(\"{log_id}\"), which now"
          f" carries only {monthly(target_bytes):.2f} GiB/mo. The equivalent"
          f" stream {', '.join(successors)} carries"
          f" {monthly(sum(successors.values())):.2f} GiB/mo and is matched by"
          " no exclusion. The documented intent was to drop this volume.",
          stale_claims,
          confidence="medium",
          flag=messages.FLAG_INTENT_INFERRED,
      )

  # --- VPC flow logs sampled above the vendor default ------------------------
  enabled = [
      c
      for c in flow_log_configs or ()
      if str(c.get("state", "")).upper() == "ENABLED"
  ]
  samplings = [
      float(c["flow_sampling"]) for c in enabled if c.get("flow_sampling")
  ]
  # The least-sampled config bounds what every config would shed. Volume per
  # config is unknown, so anything higher could claim bytes that stay.
  floor_sampling = min(samplings) if samplings else 0.0
  if floor_sampling > FLOW_LOG_TARGET_SAMPLING:
    reduction = 1.0 - FLOW_LOG_TARGET_SAMPLING / floor_sampling
    flow_claims = [
        (log_id, ALL_SEVERITIES, num_bytes * ledger.claim(log_id, reduction))
        for log_id, num_bytes in bytes_by_log.items()
        if _stream_suffix(log_id) == "vpc_flows"
    ]
    if any(b > 0 for _, _, b in flow_claims):
      add(
          "flow_log_oversampling",
          "VPC flow logs sampled above the GCP default",
          f"All {len(samplings)} enabled flow log configs with a known rate"
          f" sample at {floor_sampling:.2f} or more, against the GCP console"
          f" default of {FLOW_LOG_TARGET_SAMPLING}. Flows are still captured,"
          " at lower fidelity.",
          flow_claims,
          manual_step=(
              f"Set flow_sampling to the {FLOW_LOG_TARGET_SAMPLING} console"
              " default on the VPC flow log configs"
              " (google_compute_subnetwork.log_config.flow_sampling, or the"
              " Network Management vpcFlowLogsConfigs API)."
          ),
          confidence="medium",
      )

  # --- DEBUG severity in production ------------------------------------------
  debug_claims = []
  for (log_id, severity), num_bytes in billable_streams.items():
    if severity.upper() != "DEBUG" or is_data_access(log_id):
      continue
    stream_total = bytes_by_log[log_id]
    granted = ledger.claim(log_id, num_bytes / stream_total)
    debug_claims.append((log_id, severity, stream_total * granted))
  debug_bytes = sum(b for _, _, b in debug_claims)
  if debug_bytes > 0:
    add(
        "debug_severity",
        "DEBUG severity logs retained in production",
        f"{monthly(debug_bytes):.2f} GiB/mo of DEBUG logs across"
        f" {sum(1 for _, _, b in debug_claims if b > 0)} stream(s).",
        debug_claims,
    )

  # --- Data Access audit logs: reported, never offered -----------------------
  # Measured against what stays billed: a duplicate copy is counted once, by
  # the duplicate-routing lever.
  audit_claims = [
      (log_id, severity, v * ledger.retained(log_id))
      for (log_id, severity), v in billable_streams.items()
      if is_data_access(log_id)
  ]
  audit_bytes = sum(b for _, _, b in audit_claims)
  if audit_bytes > 0:
    add(
        "data_access_audit_logs",
        "Data Access audit logs",
        f"{monthly(audit_bytes):.2f} GiB/mo of Data Access audit logs.",
        audit_claims,
        withheld=messages.WITHHELD_DATA_ACCESS.format(gib=monthly(audit_bytes)),
        counted=False,
    )

  counted = [a for a in levers if a.counted]
  total_pct = round(sum(a.pct_of_billable for a in counted), 2)
  return {
      "status": "ok",
      "basis": {
          "window_days": window_days,
          "source": "billing/bytes_ingested + byte_count (Cloud Monitoring)",
          "byte_count_to_billed_calibration": round(calibration, 4),
          # Both sides of the calibration ratio, so Prove It can re-derive it.
          "calibration_anchor": (
              "billing_export"
              if billed_window_gib is not None and billed_window_gib > 0
              else "billing/bytes_ingested"
          ),
          "anchor_window_gib": round(billed_total / BYTES_PER_GIB, 2),
          "byte_count_window_gib": round(raw_stream_total / BYTES_PER_GIB, 2),
          "baseline_monthly_gib": round(monthly_gib, 2),
          "billable_monthly_gib": round(billable_monthly_gib, 2),
          "billable_monthly_cost_usd": price_book.baseline_cost,
      },
      # The sum of the counted actions in `reduction_actions`.
      "headline": {
          "pct_of_billable_spend": total_pct,
          "monthly_savings_usd": round(sum(a.monthly_usd for a in counted), 2),
          "monthly_savings_gib": round(sum(a.monthly_gib for a in counted), 2),
          "exceeds_sanity_ceiling": total_pct > WASTE_SANITY_CEILING_PCT,
      },
      "uncounted_total_pct": round(
          sum(a.pct_of_billable or 0.0 for a in levers if not a.counted), 2
      ),
  }, levers

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