Hour 6: Logging, monitoring, audit and cost governance

Cloud Audit Logs, organization-level log sinks, log buckets, Cloud Monitoring, budgets, billing export and Cloud Asset Inventory.
Hour 6Cloud LoggingCloud MonitoringBilling

Hour 6: Logging, monitoring, audit and cost governance

A landing zone is only trustworthy if you can answer three questions at any time: what happened, are we being told, and what does it cost. This hour builds the evidence, alerting and spend controls that the earlier hours made necessary. Hour 1 gave you a hierarchy and a billing structure, Hour 2 gave you IAM, Hour 3 gave you guardrails, and Hours 4 and 5 gave you a network. Now you will record what happens in all of it and learn to read that record.

You start with Cloud Audit Logs, the platform's own record of who did what, and learn which of the four types are on by default and how long each is kept. You then follow a log entry through the Log Router, where sinks, buckets and exclusions decide where it is stored. Next you design the centralized pattern: an organization-level aggregated sink writing into a protected logging project, with a writer identity that is granted exactly one role. After that, Cloud Monitoring turns the signals into alerts that people receive.

The second half of the hour covers cost governance (budgets that alert but do not cap, billing export to BigQuery, labels for allocation), Cloud Asset Inventory for change history and drift reporting, a hands-on lab that ties the pieces together, and a module of production cases and troubleshooting for missing logs, silent sinks, alerts that never arrive and ingestion cost spikes.

Every module follows the same ten tabs: concepts, diagrams, a step-by-step animation, commands, a lab, production practice, troubleshooting and videos, and each module ends with a five-question quiz. Use the audio buttons to hear the key terms in English.

What you will be able to do

  • Name the four Cloud Audit Log types, say which are on by default and for how long they are kept, and enable Data Access logs for one service on purpose.
  • Read an audit entry with gcloud logging read and find the principal, the method, the resource, the caller IP and the result.
  • Create a log bucket with its own retention, a sink with an inclusion filter and an exclusion, and verify that entries arrived.
  • Design a central logging architecture with an organization sink using --include-children, and grant the sink's writer identity the narrowest role on the destination.
  • Build a notification channel and a log-based alert for an audit event such as an IAM policy change.
  • Create a budget with alert thresholds, explain why a budget does not stop spend, and find cost by label in a billing export.
  • Search the resource inventory and export an asset snapshot to detect drift.
  • Triage the four classic failures: missing logs, a sink without permission, an alert that is not received, and an ingestion cost spike.

Schedule (60 minutes)

#ModuleMinutes
1Cloud Audit Logs6
2Log routing8
3Centralized logging architecture7
4Cloud Monitoring7
5Cost governance8
6Asset inventory and change history7
7Lab: org sink and budget alert10
8Production cases and troubleshooting7
Total60

What you need

  • A Google Cloud sandbox: ideally an organization with a lab folder, but a single sandbox project works for every lab (see the setup page for the project-level alternatives).
  • Access to the Billing account that pays for the sandbox, with roles/billing.costsManager or roles/billing.admin to create budgets.
  • The gcloud CLI (current release channel) or Cloud Shell, and an email address you can read for alert notifications.
  • The IDs from Hour 1: ORG_ID (if you have one), FOLDER_ID, PROJECT_ID and BILLING_ACCOUNT_ID.

What the labs create and what they cost

ResourceCreated inCost
Service accounts (to generate audit events)Modules 1 to 4Free
Custom log buckets (30-day retention)Modules 2, 3 and 7Low: only the few audit entries routed into them are billed
Log sinks (project-level, optionally organization-level)Modules 2, 3 and 7Free to create
Notification channel and log-based alert policyModules 4 and 7Free
Budget with email alertsModules 5 and 7Free
Asset export to a Cloud Storage bucket (optional)Module 6Low: a small bucket and a small file
Cost warning. Ingestion into non-_Required log buckets, Data Access logs and long retention are billed by volume. The labs keep filters narrow and retention short, so the total is usually well under a few USD per day. Budgets send alerts and do not cap spend: set one before you start, and run every cleanup step at the end. Do not enable Data Access logs for all services, and do not create an organization sink in a shared organization without approval.
Tip. If you have no organization, do not skip the organization-level modules. Read the organization commands, run their project-level equivalents, and note which controls are missing from your environment.

Setup

Logging, monitoring, audit and cost governance
Hour 6

Setup for Hour 6

This hour needs only a sandbox project for most labs. Organization-level steps are optional. Complete the checks below before you start Module 1, so the labs do not stall on access or billing.

1. Tools

  • Google Cloud CLI (current release channel). Use Cloud Shell (no installation) or install the CLI locally and run gcloud init. Update with gcloud components update if a command in this hour is missing. A few monitoring commands are in the alpha or beta tracks, and the CLI may ask to install those components.
  • An email address you can read, for the alert channel and the budget notifications. Prefer a group address in a real environment.
  • Optional: Terraform 1.x with the Google provider (pin the major version in required_providers) if you want to translate the console steps into code later in Hour 7.
gcloud --version
gcloud auth list
gcloud config list --format="value(core.account,core.project)"
Google Cloud SDK 5xx.x.x
alpha 2026.xx.xx
beta 2026.xx.xx
core 2026.xx.xx

                  Credentialed Accounts
ACTIVE  ACCOUNT
*       ana@example.com

ana@example.com  lz-lab-0001

Versions and IDs in the expected output are illustrative.

2. The sandbox project and the destination

Use a sandbox project that you are allowed to break. For the central logging labs, a second project is better: one acts as the producer and the other as the logging destination. If you only have one project, the labs still work with the sink and the bucket in the same project.

gcloud config set project PROJECT_ID
gcloud projects describe PROJECT_ID --format="value(projectId,projectNumber,parent.id,lifecycleState)"
gcloud services enable logging.googleapis.com monitoring.googleapis.com iam.googleapis.com cloudasset.googleapis.com cloudbilling.googleapis.com --project=PROJECT_ID
lz-lab-0001  123456789012  987654321098  ACTIVE
Operation "operations/acf.p2-123456789012-…" finished successfully.

Enabling these APIs is free. Cloud Logging and Cloud Monitoring are enabled by default on most projects. Cloud Asset API is used in Module 6, and the Cloud Billing API is needed for budget commands.

3. Roles you need

TaskRoleScope
Read audit logs (Admin Activity, System Event)roles/logging.viewerProject (organization for organization-wide reads)
Read Data Access logsroles/logging.privateLogViewerProject
Create buckets, sinks and exclusionsroles/logging.configWriterProject (organization for organization sinks)
Grant a sink's writer identity accessroles/resourcemanager.projectIamAdmin (or an equivalent)Destination project
Create alerting policies and channelsroles/monitoring.alertPolicyEditor and roles/monitoring.notificationChannelEditor (or roles/monitoring.editor)Scoping project
Create and read budgetsroles/billing.costsManager or roles/billing.adminBilling account
Search and export assetsroles/cloudasset.viewer (search) and roles/cloudasset.owner or equivalent for exportsProject, folder or organization

In a sandbox the Owner role on the project covers all project-level rows. Billing roles are separate and are granted on the billing account, so confirm them first.

4. Billing and the budget (do this first)

gcloud billing accounts list
gcloud billing projects describe PROJECT_ID
ACCOUNT_ID            NAME              OPEN  MASTER_BILLING_ACCOUNT
0X0X0X-0X0X0X-0X0X0X  Platform billing  True

billingAccountName: billingAccounts/0X0X0X-0X0X0X-0X0X0X
billingEnabled: true
name: projects/lz-lab-0001/billingInfo
projectId: lz-lab-0001

If billingEnabled is false, link the project with gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID (Hour 1). Create a small budget on the sandbox before you run any lab; Module 5 shows the command. A budget sends alerts and does not cap spend. If you cannot see a billing account, ask the billing administrator for roles/billing.viewer on it and for a budget created on your behalf.

5. If you do not have an organization

  • Audit logs and routing. Everything in Modules 1 and 2 works in a single project. In Module 3 use a project-level sink from the producer project to a log bucket in the logging project instead of an organization sink. The writer identity grant is identical.
  • Organization sinks, folder sinks and --include-children. These need an organization. Read the commands and answer the design questions on paper.
  • Monitoring. A metrics scope works with ordinary projects. Alerting, channels and log-based alerts do not need an organization.
  • Budgets. They need a billing account, not an organization. If the billing account belongs to someone else, ask them to create the budget or to grant the role.
  • Asset inventory. Use --scope=projects/PROJECT_ID instead of --scope=organizations/ORG_ID.
gcloud organizations list
Listed 0 items.

Listed 0 items. means that you work without an organization. This is a normal result for a personal account and does not block the labs.

6. Quick access checks

gcloud logging logs list --project=PROJECT_ID --limit=3
gcloud logging buckets list --project=PROJECT_ID
gcloud logging sinks list --project=PROJECT_ID
gcloud alpha monitoring channels list --project=PROJECT_ID

All four should return without a permission error (an empty list is fine). A PERMISSION_DENIED error names the missing permission: request the matching role from the table above. If gcloud alpha asks to install components, answer yes, or use the console for the monitoring steps.

7. Cleanup habit

Each module lab ends with a cleanup block. Keep a note of what you create, using a label or a name prefix such as lab- (for example lab-audit, lab-audit-sink), so you can find leftovers with gcloud logging buckets list, gcloud logging sinks list and gcloud logging metrics list at the end of the day.

Safety. Use only sandbox projects. Do not paste real secrets or key files into any command. Never create an organization-level sink, change the _Default or _Required configuration of a shared project, or enable Data Access logs for all services without approval from the platform owner.

Module 1 · Cloud Audit Logs

00–06 · Admin Activity, Data Access, System Event and Policy Denied logs, and how to read who did what
Audit logsAdmin ActivityData Accessgcloud logging read6 min
Learning objectives
  • Name the four audit log types, say which are on by default, and say how long each is kept.
  • Read an audit log entry and find the principal, the method, the resource and the result.
  • Query audit logs with gcloud logging read and a filter, and enable Data Access logs for a service on purpose.

The short answer

Cloud Audit Logs are structured log entries that Google Cloud services write automatically for administrative actions and, if you enable them, for data access. They answer the audit question: who (principal) did what (method) on which resource, when, from where (caller IP) and with what result (status). They are part of Cloud Logging, so every tool you will meet in this hour (sinks, buckets, log-based metrics, alerts) works on them.

What: the four audit log types

TypeLog ID (after cloudaudit.googleapis.com%2F)What it recordsOn by default?Stored in
Admin ActivityactivityAPI calls and actions that modify configuration or metadata (create a VM, set an IAM policy, change a firewall rule)Yes, always. Cannot be disabled or excluded._Required bucket, 400 days, free
System Eventsystem_eventGoogle system actions that change resources, not a user call (for example a live migration)Yes, always. Cannot be disabled or excluded._Required bucket, 400 days, free
Data Accessdata_accessADMIN_READ (read configuration), DATA_READ and DATA_WRITE (read or write user data)No, except BigQuery. Must be enabled per service._Default bucket, 30 days by default, billed as ingestion
Policy DeniedpolicyRequests denied because of a security policy (VPC Service Controls, IAM deny policies)Yes. Cannot be disabled, but can be excluded from storage._Default bucket, 30 days by default, billed as ingestion

The full log name has the form projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity. The same entries exist at folder and organization level for organization-level resources, for example organizations/ORG_ID/logs/cloudaudit.googleapis.com%2Factivity for a change to an organization policy.

How it works internally

  1. A caller sends a request to a Google Cloud API (console click, gcloud, Terraform and client libraries all end up here).
  2. The service authenticates and authorises the call with IAM, then runs it.
  3. The service writes an audit LogEntry with a protoPayload of type google.cloud.audit.AuditLog. The payload includes the principal, the method, the resource, the request metadata and the status.
  4. The entry reaches the Log Router. Sinks decide where copies go. The built-in _Required sink stores Admin Activity and System Event logs; the _Default sink stores most other logs, including Data Access and Policy Denied.

Important fields in an entry:

FieldMeaning
protoPayload.authenticationInfo.principalEmailWho made the call (user or service account)
protoPayload.authenticationInfo.serviceAccountDelegationInfoImpersonation chain when one identity acts as another
protoPayload.serviceNameThe API, for example iam.googleapis.com
protoPayload.methodNameThe operation, for example google.iam.admin.v1.CreateServiceAccount or SetIamPolicy
protoPayload.resourceNameThe target, for example projects/PROJECT_ID/serviceAccounts/…
protoPayload.requestMetadata.callerIpSource address of the call
protoPayload.authorizationInfo[]Each permission checked, with granted true or false
protoPayload.statusResult; an empty status means success, code: 7 is PERMISSION_DENIED

Why it is needed

  • Security investigation. After an incident you need to reconstruct the sequence of calls.
  • Compliance. Many standards require a retained record of administrative changes and of access to sensitive data.
  • Operations. "Who deleted the firewall rule?" is answered in one query instead of a meeting.
  • Detection. Log-based metrics and alerts (Module 4) are built on audit entries, for example an alert whenever an IAM policy changes.

When to enable Data Access logs

Data Access logs can be very large, because every read of every object may produce an entry. Enable them where the data or the permission is sensitive: Cloud KMS, Secret Manager, projects holding regulated data, IAM and Resource Manager reads (ADMIN_READ). For high-volume, low-risk services, keep them off or enable only DATA_WRITE. Use exempted members to skip known noisy service accounts. Set the choice in code, at organization or folder level when you want consistency, and budget for the ingestion.

What it is confused with

Often confused withDifference
Application logsWritten by your code or by agents on a VM. Audit logs are written by the platform about API calls, not about what your code did internally.
VPC Flow Logs, firewall logsNetwork telemetry about packets and connections. Audit logs record API calls such as creating or changing a firewall rule, not the traffic itself.
Access Transparency logsRecord actions by Google personnel on your content. Audit logs record your own principals' actions.
Cloud Asset Inventory historyShows what a resource looked like at a time (Module 6). Audit logs show who changed it and how.
Google Workspace or Cloud Identity audit logsSign-in, admin console and directory events. They live in the Admin console and Reports API; they can be shared to Cloud Logging, but they are not Cloud Audit Logs.

Common misunderstandings

"Audit logging is on, so reads are recorded." Only Admin Activity and System Event are always on. A storage.objects.get by an attacker is invisible until Data Access logs are enabled for Cloud Storage, and nothing is back-filled.
"The console is not covered." Console actions call the same APIs, so they are logged with the user's email. The userAgent field shows the console or the tool.
"400 days is enough for everything." The 400-day _Required retention is fixed. If your regulation needs longer, or needs Data Access entries kept longer than the _Default 30 days, route a copy to a custom bucket or to Cloud Storage (Modules 2 and 3).
Caller console · gcloud · Terraform Google Cloud API IAM check, run the call Cloud Audit Logs builds the AuditLog entry Log Router sinks and exclusions _Required bucket Admin Activity + System Event 400 days, fixed _Default bucket Data Access + Policy Denied 30 days, editable Your sinks custom bucket · Cloud Storage BigQuery · Pub/Sub You read entries with Logs Explorer or gcloud logging read, and you filter on logName, methodName and principalEmail. Data Access logs exist only after you enable them, and only for calls made after that moment. The _Required sink cannot be edited, so the base audit trail cannot be switched off by a project owner.

Figure 1. From an API call to a stored audit entry. The Log Router decides which bucket or destination receives a copy.

What do you need to know? Who changed it? create, update, delete, SetIamPolicy Who read the data? objects, rows, secrets needs Data Access on Why was it blocked? VPC-SC or deny policy policy log Did Google act? live migration, automatic system change …%2Factivity …%2Fdata_access …%2Fpolicy …%2Fsystem_event Start with activity: it is always present and answers most "who did it" questions.

Figure 2. Choose the log by the question. Most investigations begin with the activity log; the other three answer narrower questions.

Look at the first diagram from left to right: the same entry is created for every caller, and the only thing that changes is where the Log Router sends copies. Look at the second diagram when you write a filter: the log name is the cheapest way to narrow a query.

The animation follows a single administrative call from the engineer's terminal to the moment the entry is stored and read back. Watch step 2: the audit entry is produced by the platform, not by anything you installed, and step 5 shows why the base trail cannot be removed by a project owner.

All commands read logs unless marked as a write. Run them in Cloud Shell or any shell with the gcloud CLI (current release channel). Reading logs needs roles/logging.viewer (Admin Activity and System Event) or roles/logging.privateLogViewer (Data Access). Reading costs nothing beyond API quota. IDs in the expected output are illustrative.

gcloud logging read (Admin Activity for the last day)

Purpose. Shows the most recent administrative changes in a project.

gcloud logging read 'logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity"' \
  --project=PROJECT_ID \
  --freshness=1d \
  --limit=5 \
  --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.resourceName)"
TIMESTAMP                       PRINCIPAL_EMAIL        METHOD_NAME                                 RESOURCE_NAME
2026-11-25T09:14:03.118Z        ana@example.com        google.iam.admin.v1.CreateServiceAccount    projects/lz-lab-0001/serviceAccounts/audit-demo@lz-lab-0001.iam.gserviceaccount.com
2026-11-25T08:51:40.502Z        tf-platform@lz-boot.iam.gserviceaccount.com  v1.compute.firewalls.patch   projects/lz-lab-0001/global/firewalls/allow-iap

Flags. The first argument is the filter in the Logging query language. --freshness limits the age of entries (default is 1 day when you give no time filter in some versions, so state it). --limit caps the number of entries. --format picks fields; use json or yaml to see everything. Cost: free to read.

Common errors. An empty result with no error means the filter matched nothing (check the log name encoding %2F, the project and --freshness). PERMISSION_DENIED means you lack roles/logging.viewer. Invalid filter usually means a missing quote or a lowercase and; operators AND, OR, NOT must be uppercase.

gcloud logging read (who changed IAM policies, with the caller IP)

Purpose. Finds every SetIamPolicy call and shows the person, the caller IP and the target. This is the single most useful audit query in a landing zone.

gcloud logging read 'protoPayload.methodName:"SetIamPolicy" AND logName:"cloudaudit.googleapis.com%2Factivity"' \
  --project=PROJECT_ID --freshness=7d --limit=20 \
  --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.requestMetadata.callerIp,protoPayload.resourceName)"
TIMESTAMP                 PRINCIPAL_EMAIL      CALLER_IP     RESOURCE_NAME
2026-11-24T16:02:11.870Z  ana@example.com      203.0.113.10  projects/lz-lab-0001
2026-11-22T10:31:45.004Z  tf-iam@lz-boot.iam.gserviceaccount.com  198.51.100.7  folders/987654321098

Flags. The colon operator (:) means "contains", which matches names with a version prefix such as v1.compute.firewalls.patch. Production use. Run the same filter at organization level with --organization=ORG_ID (requires roles/logging.viewer on the organization) to see changes across all projects, and turn it into an alert in Module 4. Cost: free.

gcloud logging read (denied requests)

Purpose. Shows calls that failed with PERMISSION_DENIED or were blocked by a policy. Use it when a pipeline fails and the error text is unclear.

gcloud logging read 'protoPayload.status.code=7 OR logName:"cloudaudit.googleapis.com%2Fpolicy"' \
  --project=PROJECT_ID --freshness=1d --limit=10 \
  --format="table(timestamp,logName.basename(),protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.status.message)"
TIMESTAMP                 LOG_NAME                                PRINCIPAL_EMAIL        METHOD_NAME                  MESSAGE
2026-11-25T09:30:12.001Z  cloudaudit.googleapis.com%2Factivity    dev@example.com        v1.compute.instances.insert  Required 'compute.instances.create' permission for 'projects/lz-lab-0001/zones/europe-west1-b/instances/vm1'
2026-11-25T09:05:44.700Z  cloudaudit.googleapis.com%2Fpolicy      build@lz-ci.iam.gserviceaccount.com  google.storage.objects.get  Request is prohibited by organization's policy. vpcServiceControlsUniqueIdentifier: …

Common errors. Code 7 is PERMISSION_DENIED; code 16 is UNAUTHENTICATED. The vpcServiceControlsUniqueIdentifier value is what you quote when you look up a VPC Service Controls violation (Hour 3).

gcloud logging logs list

Purpose. Lists which log IDs exist in a project, which tells you at a glance whether Data Access or Policy Denied entries have ever been written.

gcloud logging logs list --project=PROJECT_ID
NAME
projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Factivity
projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Fdata_access
projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Fsystem_event

Cost: free. A log that never appears here has never received an entry in the retained window.

Enable Data Access logs (write, changes IAM policy)

Purpose. Adds an auditConfigs block to the project IAM policy so Cloud Storage records reads and writes. Cost: the command is free; the resulting log entries are billed as ingestion into the _Default bucket, so start with one service and watch the volume.

gcloud projects get-iam-policy PROJECT_ID --format=yaml > policy.yaml
# Edit policy.yaml: add the block below at the top level, keep bindings and etag as exported.
gcloud projects set-iam-policy PROJECT_ID policy.yaml
auditConfigs:
- service: storage.googleapis.com
  auditLogConfigs:
  - logType: ADMIN_READ
  - logType: DATA_READ
  - logType: DATA_WRITE
    exemptedMembers:
    - serviceAccount:backup-job@PROJECT_ID.iam.gserviceaccount.com
Updated IAM policy for project [lz-lab-0001].
auditConfigs:
- auditLogConfigs:
  - logType: ADMIN_READ
  - logType: DATA_READ
  - logType: DATA_WRITE
    exemptedMembers:
    - serviceAccount:backup-job@lz-lab-0001.iam.gserviceaccount.com
  service: storage.googleapis.com
bindings: …
etag: BwY…

Flags and risk. set-iam-policy replaces the whole policy. If the file has an old etag, the call fails with a conflict (good). If you remove bindings by mistake, access is removed (bad), so review the diff. Use allServices in service only when you accept the volume. The same auditConfigs form exists for gcloud organizations and gcloud resource-manager folders. In production, set it in Terraform with google_project_iam_audit_config (or the organization and folder versions), not by hand. Check gcloud projects set-iam-policy --help for the flags in your SDK version.

Production use. Save the four or five queries you reuse (IAM changes, firewall changes, service account key creation, denied calls) as Logs Explorer saved queries or as log-based alerts. A query you have to rediscover during an incident is a query you will not write correctly under pressure.

Lab: generate an audit event and read it back (about 10 minutes, free)

Goal. Create a harmless administrative event, find it in the Admin Activity log, and read the principal, method and resource fields.

Prerequisites. A sandbox project (PROJECT_ID) where you hold roles/iam.serviceAccountAdmin (or Owner) and roles/logging.viewer. The IAM API enabled (gcloud services enable iam.googleapis.com, free). A budget set first (Module 5 shows how; at minimum make sure you know which billing account pays for the project). No organization is needed.

  1. Confirm the identity and the project: gcloud config list --format="value(core.account,core.project)". Set the project if needed with gcloud config set project PROJECT_ID.
  2. Create a service account. This is an Admin Activity event. A service account without keys or role bindings has no permissions and no cost.
    gcloud iam service-accounts create audit-demo --display-name="Audit lab demo" --project=PROJECT_ID
  3. Wait about a minute, then read the event:
    gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount" AND protoPayload.resourceName:"audit-demo"' \
      --project=PROJECT_ID --freshness=1h --limit=1 --format=json
  4. In the JSON, find and write down: protoPayload.authenticationInfo.principalEmail, protoPayload.requestMetadata.callerIp, protoPayload.requestMetadata.callerSuppliedUserAgent, protoPayload.status (empty means success) and logName.
  5. Generate a denied event on purpose: gcloud iam service-accounts delete nonexistent@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet. It fails because the account does not exist (NOT_FOUND, code 5), and the failed call is still recorded. Then run the query from the command tab with protoPayload.status.code>0 and find it.
  6. Open Logs Explorer in the console, switch to the Query editor, paste the filter from step 3 and press Run query. Compare the console view with the JSON.
  7. Check whether Data Access logs exist: gcloud logging logs list --project=PROJECT_ID. Note which of activity, data_access, system_event, policy are present, and explain why.

Expected result. One entry whose principalEmail is your account, methodName is google.iam.admin.v1.CreateServiceAccount, and resourceName ends with serviceAccounts/audit-demo@PROJECT_ID.iam.gserviceaccount.com. Another entry for the failed delete with a non-zero status code.

[
  {
    "logName": "projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Factivity",
    "protoPayload": {
      "authenticationInfo": { "principalEmail": "ana@example.com" },
      "methodName": "google.iam.admin.v1.CreateServiceAccount",
      "resourceName": "projects/lz-lab-0001/serviceAccounts/…",
      "serviceName": "iam.googleapis.com"
    },
    "severity": "NOTICE"
  }
]

Verification. If step 3 returns [], wait another minute (entries can take up to a few minutes), confirm the project with --project, and re-run with --freshness=1d.

Cost. Free. Admin Activity logs are not billed, a service account is free, and reading logs is free.

Cleanup.

gcloud iam service-accounts delete audit-demo@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet

The deletion creates a further Admin Activity entry; that is expected and proves the trail records cleanup too.

Stretch (optional): Data Access on a test bucket

Enable DATA_READ and DATA_WRITE for storage.googleapis.com as in the command tab, create a bucket with gcloud storage buckets create gs://UNIQUE_BUCKET_NAME --location=REGION --uniform-bucket-level-access, upload a tiny file with gcloud storage cp, and read the data_access entries. The volume is tiny, so the cost is low (usually well under a few USD per day for this lab). Remove the audit config and delete the bucket afterwards. Budgets send alerts and do not cap spend.

Real cases (typical patterns)

  • The deleted firewall rule. An ingress rule disappeared on a Friday and an application became reachable from the internet. The platform team ran a saved query on v1.compute.firewalls.delete, found a service account used by a deployment pipeline, and traced it to a Terraform plan that nobody had reviewed. The fix was a pull-request gate, not a new log; the log made the diagnosis take minutes.
  • Data Access enabled everywhere. A team turned on allServices Data Access logs for the whole organization to satisfy an auditor. Logging ingestion became the largest line of the monthly bill, driven by one batch job reading millions of objects. The corrected design enabled Data Access for KMS, Secret Manager, IAM and the regulated projects only, added exempted members for known batch identities, and kept a short retention in _Default with a copy of the sensitive entries in a longer-lived bucket.
  • Investigation without a baseline. After a credential leak, a company could prove which administrative calls the stolen key had made, but not which objects it had read, because Data Access was off for Cloud Storage. The lesson recorded in their runbook: decide what you want to be able to answer before the incident, and enable the logs that answer it.

Practices

  • Enable the Data Access types you need through code at organization or folder level, so new projects inherit them, and review the list every quarter.
  • Route audit logs to a protected, central location (Modules 2 and 3), because a project owner can delete a project and its _Default data with it.
  • Use groups and service accounts with clear names, so principalEmail tells a reviewer who or what acted. Shared accounts defeat the audit trail.
  • Tag impersonation: when a pipeline impersonates a service account, the entry shows the chain in serviceAccountDelegationInfo. Teach reviewers to read it.
  • Keep a small set of tested queries in the incident runbook: IAM changes, organization policy changes, service account key creation, firewall and route changes, sink and exclusion changes, denied calls.

Security notes

Protect the audit trail itself. Anyone who can edit sinks, exclusions or buckets (roles/logging.admin, roles/owner) can change what is kept in the editable buckets. Give that role to a small group, alert on UpdateSink, DeleteSink and bucket updates, and keep a copy in a project that application teams cannot administer.
Audit logs contain sensitive metadata. Entries include IP addresses, resource names, and sometimes request fields. Grant roles/logging.privateLogViewer (needed for Data Access logs) sparingly, and use log views (Module 3) to scope access.

Symptoms and first checks

SymptomLikely causeFirst check
gcloud logging read returns nothing for an action you know happenedWrong log name encoding, wrong project, entry older than --freshness, or the entry is at folder or organization levelRun with only logName:"cloudaudit" and --freshness=1d; then try --organization=ORG_ID
No data_access log existsData Access is not enabled for that service, or it was enabled recentlygcloud projects get-iam-policy PROJECT_ID --format="yaml(auditConfigs)"
Entry is found but the principal is a Google-owned accountA Google service agent or system performed the action on your behalfRead serviceAccountDelegationInfo and the methodName; check System Event logs
PERMISSION_DENIED reading Data Access logsMissing roles/logging.privateLogViewergcloud projects get-iam-policy PROJECT_ID, filtered to your identity
Policy Denied entries are missingAn exclusion on _Default removes them, or no policy denied anythinggcloud logging sinks describe _Default and look at exclusions
Cannot find old entries after 30 daysData Access and Policy Denied are kept 30 days in _Defaultgcloud logging buckets describe _Default --location=global and check retentionDays
set-iam-policy fails with a conflictStale etag because someone changed the policy after your exportExport again, merge the auditConfigs block, re-apply

Triage order

  1. Confirm the scope: project, folder or organization, and the correct --project or --organization flag.
  2. Confirm the log type and the exact log name (%2Factivity, %2Fdata_access, %2Fpolicy, %2Fsystem_event).
  3. Widen the time window, then narrow by methodName and resourceName.
  4. If the entry should exist but does not, check whether the log was ever enabled and whether an exclusion or a short retention removed it.
  5. Read the status and authorizationInfo of the entry to see which permission was checked and whether it was granted.

Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.

Official reading: Cloud Audit Logs overview · Configure Data Access audit logs · Logging query language.

or score ≥ 70% on the quiz

Module 2 · Log routing

06–14 · Log Router, sinks, log buckets, exclusions, and retention of _Required and _Default
Log RouterSinksLog bucketsExclusionsRetention8 min
Learning objectives
  • Explain how the Log Router uses inclusion filters, exclusion filters and sinks to decide where each log entry is stored.
  • Create a log bucket with a chosen retention and a sink that routes a filtered set of logs into it.
  • State what _Required and _Default are, what you can and cannot change, and where the cost comes from.

The short answer

Log routing decides where each log entry ends up. All entries go to the Log Router (日志路由器). The router tests every entry against every sink (日志接收器) in the resource that produced it. A sink has a destination, an inclusion filter (what to keep) and zero or more exclusion filters (what to drop from this sink). If the entry passes, a copy is written to the destination. One entry can therefore be stored in several places, each with its own retention and cost.

What: the building blocks

PieceWhat it isYou can change it?
_Required bucket and sinkHolds Admin Activity, System Event and Access Transparency logs, 400 days, no ingestion chargeNo. Not editable, no exclusions, retention fixed
_Default bucket and sinkHolds every other log (application, Data Access, Policy Denied, platform logs); 30 days by defaultYes: retention, exclusions, or disable the sink
Custom log bucketYour bucket with a location, retention, optional CMEK, optional Log Analytics, optional lockYes (location cannot change)
SinkRouting rule: destination, filter, exclusions, writer identityYes
Log viewA saved filter over a bucket used to grant access to a subset of its entriesYes

Destinations

DestinationFormat of the destination argumentWriter role neededTypical use
Log bucketlogging.googleapis.com/projects/PROJECT_ID/locations/LOCATION/buckets/BUCKET_IDroles/logging.bucketWriterCentral retention, Logs Explorer, Log Analytics
Cloud Storagestorage.googleapis.com/BUCKET_NAMEroles/storage.objectCreatorCheap long-term archive, retention policy or lock
BigQuery datasetbigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_IDroles/bigquery.dataEditorSQL analysis, reports
Pub/Sub topicpubsub.googleapis.com/projects/PROJECT_ID/topics/TOPIC_IDroles/pubsub.publisherStream to a SIEM or another cloud
Another project's log bucketsame as log bucketroles/logging.bucketWriter on the destination projectCentral logging project (Module 3)

How it works internally

  1. An entry is written to a resource, for example a project. It reaches the Log Router of that resource.
  2. For each sink on that resource the router evaluates the inclusion filter. If it does not match, the sink ignores the entry. If the filter is empty, the sink matches every entry (this is the _Default sink shape).
  3. If the entry matches, the sink's exclusion filters are evaluated. If any exclusion matches, the entry is dropped for this sink only (optionally sampled with sample(insertId, 0.9)).
  4. If the entry passes, the router writes it to the destination with the sink's writer identity.
  5. The destination applies its own storage rules: log bucket retention, Cloud Storage lifecycle or retention policy, BigQuery table expiration.

Every sink works independently. This is why you can keep audit logs in a locked bucket for years and, at the same time, drop DEBUG noise from _Default to control cost.

Retention and cost

  • Ingestion. Entries stored in a log bucket other than _Required are billed by volume ingested. Routing a copy to a second bucket means a second ingestion for that copy. Exclusions are the control that reduces the bill.
  • Storage and retention. Retention beyond the default period is billed by the volume kept. Choose the shortest retention that your rules and investigations require.
  • Cloud Storage and BigQuery. Billed as normal storage and, for BigQuery, queries. A sink to Cloud Storage or BigQuery does not incur Logging ingestion for that copy; the destination service bills its own storage.
  • Do not memorise prices. Use the pricing page and the Billing reports (Module 5) to measure.

When to use each approach

NeedApproach
Keep audit logs longer than 30 days with search in the consoleCustom log bucket (for example 365 days) plus a sink for cloudaudit logs
Prove logs were not tampered with for yearsCloud Storage with a retention policy, locked, or a locked log bucket
Analyse with SQLLog bucket with Log Analytics enabled, or a BigQuery sink
Send to a SIEMPub/Sub sink and a subscriber
Cut noise costExclusion on _Default (for example health checks, DEBUG)

What it is confused with

Often confused withDifference
Exclusion filter vs inclusion filterInclusion says what the sink keeps; exclusion says what to remove from that selection. Both belong to the sink.
Log bucket vs Cloud Storage bucketA log bucket is Cloud Logging storage that Logs Explorer and Log Analytics can query. A Cloud Storage bucket receives files exported by a sink.
Log views vs IAM on the bucketA view narrows what a reader can see inside a bucket; IAM on the project decides who can read at all.
Retention vs lockRetention sets how long entries are kept; locking a bucket makes the retention setting permanent.

Common misunderstandings

"Excluding at _Default stops cost everywhere." It reduces only that sink. A custom sink with a broad filter still ingests the same entries.
"The sink is a copy, so I can delete the source." Deleting a project removes its buckets. Route to a destination outside the project if the data must survive the project.
"Locking a bucket is just another setting." Locking a log bucket makes its retention permanent. You cannot unlock it, and you cannot delete it until all data has aged out. Lock only after the retention period is agreed.
Log entries audit · app · platform Log Router per sink: include? then exclude? then write _Required sink cloudaudit activity + system_event _Default sink all else, minus exclusions Sink: audit-archive filter: cloudaudit Sink: errors-to-siem filter: severity >= ERROR _Required400 days _Default30 days audit-365365 days Pub/Subto the SIEM

Figure 1. One entry, several independent sinks. An audit entry can be stored in _Required, in a long-lived custom bucket and in a SIEM at the same time.

Entry arrives at a sink Inclusion filter match? yes Exclusion filters any match? no Write copy writer identity no yes Not stored by this sink (other sinks decide for themselves) Filtering happens before the write, so excluded entries are not billed at this destination. A write can still fail after the filter passes: check the writer identity's permission on the destination.

Figure 2. The two questions each sink asks. Read the first diagram for the big picture and this one when you write a filter.

Look at the fan-out on the first diagram: nothing in one sink depends on another. In the second diagram, note that a successful filter is not yet a successful write; the writer identity decides that.

The animation follows one ERROR entry through the Log Router. Each sink decides on its own, and each destination keeps its own copy with its own retention. Watch step 4, where the sink uses its writer identity, because that is the permission that most often breaks a new sink.

Most commands in this tab write configuration. Creating buckets and sinks is free; ingestion into non-_Required buckets is billed by volume, so keep filters narrow in labs. IDs in the expected output are illustrative. Roles: roles/logging.configWriter to create sinks and buckets, roles/logging.viewer to list.

gcloud logging buckets list and describe

Purpose. Shows the buckets of a project and their retention.

gcloud logging buckets list --project=PROJECT_ID
gcloud logging buckets describe _Default --location=global --project=PROJECT_ID
LOCATION  BUCKET_ID  RETENTION_DAYS  LIFECYCLE_STATE  LOCKED
global    _Default   30              ACTIVE           False
global    _Required  400             ACTIVE           True

createTime: '2026-11-01T08:00:00.123456789Z'
lifecycleState: ACTIVE
name: projects/lz-lab-0001/locations/global/buckets/_Default
retentionDays: 30

Flags. --location is required for describe (use global unless you created a regional bucket). Column names can differ in your SDK version. Cost: free.

gcloud logging buckets create (write)

Purpose. Creates a custom log bucket with its own retention. Cost: creating it is free; entries ingested into it are billed.

gcloud logging buckets create audit-365 \
  --location=global \
  --retention-days=365 \
  --description="Audit logs kept 365 days" \
  --project=PROJECT_ID
Created bucket [audit-365].
createTime: '2026-11-25T09:40:02.000Z'
description: Audit logs kept 365 days
lifecycleState: ACTIVE
name: projects/lz-lab-0001/locations/global/buckets/audit-365
retentionDays: 365

Flags. --location is where the data is stored and cannot be changed later; pick it with your data-residency rule (global or a region such as europe-west1). --retention-days sets how long entries are kept. Optional flags exist for CMEK, Log Analytics and locking; check gcloud logging buckets create --help for the flags in your SDK version.

Common errors. ALREADY_EXISTS when a bucket ID was used before and is in the 7-day deleted state (deleted buckets stay recoverable for a short period, and the ID is reserved). PERMISSION_DENIED needs logging.buckets.create.

gcloud logging buckets update (write)

Purpose. Changes retention of an existing bucket, including _Default.

gcloud logging buckets update _Default --location=global --retention-days=60 --project=PROJECT_ID
Updated bucket [_Default].
retentionDays: 60

Production use. Shortening retention does not instantly delete data in all cases, but entries older than the new period become eligible for deletion; plan a change window and confirm with legal. Lengthening is safe and billed from then on.

gcloud logging sinks create (write)

Purpose. Creates a sink that routes matching entries to the bucket.

gcloud logging sinks create audit-to-365 \
  logging.googleapis.com/projects/PROJECT_ID/locations/global/buckets/audit-365 \
  --log-filter='logName:"logs/cloudaudit.googleapis.com"' \
  --description="Copy audit logs to the 365-day bucket" \
  --project=PROJECT_ID
Created [https://logging.googleapis.com/v2/projects/lz-lab-0001/sinks/audit-to-365].
Please remember to grant `serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com` the Logs Bucket Writer role on the destination if it is in a different project.

Flags. The first argument is the sink name and the second is the destination. --log-filter is the inclusion filter. The printed writer identity is the principal to authorise on the destination. The message wording varies by SDK version. Cost: the sink is free; the bucket ingestion is billed.

Common errors. Invalid destination means the destination string does not match the expected format. Invalid filter means a syntax error such as an unbalanced quote.

gcloud logging sinks describe and list

Purpose. Shows the filter, destination, exclusions and writer identity.

gcloud logging sinks list --project=PROJECT_ID
gcloud logging sinks describe audit-to-365 --project=PROJECT_ID
NAME           DESTINATION                                                                         FILTER
_Default       logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/_Default       NOT LOG_ID("cloudaudit.googleapis.com/activity") AND NOT LOG_ID("externalaudit.googleapis.com/activity") AND NOT LOG_ID("cloudaudit.googleapis.com/system_event") AND NOT LOG_ID("externalaudit.googleapis.com/system_event") AND NOT LOG_ID("cloudaudit.googleapis.com/access_transparency") AND NOT LOG_ID("externalaudit.googleapis.com/access_transparency")
_Required      logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/_Required      LOG_ID("cloudaudit.googleapis.com/activity") OR …
audit-to-365   logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/audit-365      logName:"logs/cloudaudit.googleapis.com"

createTime: '2026-11-25T09:41:10.000Z'
description: Copy audit logs to the 365-day bucket
destination: logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/audit-365
filter: logName:"logs/cloudaudit.googleapis.com"
name: audit-to-365
writerIdentity: serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com

The built-in sinks show that _Default is "everything except the logs that _Required keeps". Cost: free.

gcloud logging sinks update (write): add an exclusion on _Default

Purpose. Drops noisy low-severity entries from _Default to reduce ingestion.

gcloud logging sinks update _Default \
  --add-exclusion=name=drop-debug,filter='severity<=DEBUG',description="Drop DEBUG entries" \
  --project=PROJECT_ID

Flags. The exclusion has a name and a filter, and may carry a description or be disabled. Update flags differ between SDK versions; check gcloud logging sinks update --help. Warning. Never exclude cloudaudit.googleapis.com%2Fdata_access or %2Fpolicy entries you rely on for investigations without confirming a copy exists elsewhere.

gcloud logging read from a bucket

Purpose. Verifies that routed entries arrived.

gcloud logging read 'logName:"cloudaudit.googleapis.com"' \
  --bucket=audit-365 --location=global --view=_AllLogs \
  --project=PROJECT_ID --limit=3 --freshness=1d \
  --format="table(timestamp,protoPayload.methodName)"

Flags. --bucket, --location and --view read from a specific bucket instead of the default view; _AllLogs is the view that shows every entry in the bucket. Cost: free.

Production use. Manage buckets, sinks and exclusions in Terraform (google_logging_project_bucket_config, google_logging_project_sink, google_logging_organization_sink), review changes by pull request and alert on any manual change (Module 4).

Lab: a custom bucket and a sink, verified end to end (about 15 minutes, low cost)

Goal. Create a log bucket with 30-day retention, route audit logs to it with a sink, generate an event and read it back from the bucket. IDs in the expected output are illustrative.

Prerequisites. A sandbox project (PROJECT_ID), roles/logging.configWriter and roles/logging.viewer, a budget in place (budgets send alerts and do not cap spend), and the gcloud CLI. No organization is required for a project-level sink.

  1. List the current buckets and sinks to see the baseline.
    gcloud logging buckets list --project=PROJECT_ID
    gcloud logging sinks list --project=PROJECT_ID
  2. Create the bucket with a short retention. Short retention keeps the cost low.
    gcloud logging buckets create lab-audit --location=global --retention-days=30 --project=PROJECT_ID
    Verify: gcloud logging buckets describe lab-audit --location=global --project=PROJECT_ID --format="value(retentionDays)" must print 30.
  3. Create the sink for audit logs of this project.
    gcloud logging sinks create lab-audit-sink \
      logging.googleapis.com/projects/PROJECT_ID/locations/global/buckets/lab-audit \
      --log-filter='logName:"logs/cloudaudit.googleapis.com%2Factivity"' --project=PROJECT_ID
    Verify: gcloud logging sinks describe lab-audit-sink --project=PROJECT_ID --format="value(writerIdentity,destination)" prints a serviceAccount:service-…@gcp-sa-logging.iam.gserviceaccount.com identity and the bucket path.
  4. Generate an event and wait one to two minutes.
    gcloud iam service-accounts create route-demo --project=PROJECT_ID
  5. Read the entry from the bucket, not from _Default or _Required.
    gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount"' \
      --bucket=lab-audit --location=global --view=_AllLogs --project=PROJECT_ID --freshness=1h --limit=1 \
      --format="value(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"
  6. Add an exclusion to _Default in the console: Logging, Log Router, the _Default sink, Edit sink, add exclusion drop-debug with filter severity<=DEBUG. Confirm with gcloud logging sinks describe _Default --project=PROJECT_ID that the exclusion is listed. This is metadata only.
  7. Explain in your notes: which buckets hold the entry for the service account creation? (Answer: _Required and lab-audit. It is not in _Default, because the _Default sink leaves out the activity log.)

Expected result. Step 5 prints one line with a timestamp, your email and the service account resource name. If your project already sends to the sink destination in another project, add the roles/logging.bucketWriter grant from Module 3; sinks to a bucket in the same project normally need no extra grant.

2026-11-25T10:02:41.554Z  ana@example.com  projects/lz-lab-0001/serviceAccounts/route-demo@lz-lab-0001.iam.gserviceaccount.com

Verification. No output after three minutes means a routing problem. Read the sink description, check the filter spelling, and look for sink errors: gcloud logging read 'protoPayload.serviceName="logging.googleapis.com" AND severity>=ERROR' --project=PROJECT_ID --freshness=1h.

Cost. Low (usually well under a few USD per day for this lab). Only the audit entries copied into lab-audit are billed as ingestion, and the volume is a handful of entries.

Cleanup.

gcloud logging sinks delete lab-audit-sink --project=PROJECT_ID --quiet
gcloud logging buckets delete lab-audit --location=global --project=PROJECT_ID --quiet
gcloud iam service-accounts delete route-demo@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet

Deleted buckets go to a short recovery period, so the bucket ID is not reusable immediately. Remove the drop-debug exclusion from _Default if you do not want to keep it.

Real cases (typical patterns)

  • The quiet exclusion. A cost-saving exclusion on _Default used the filter severity<WARNING and, through a copy-paste, also matched the Data Access log for Secret Manager. Six months later an investigation found no read events. The remedy was a rule that every exclusion is a Terraform resource with a named reviewer, a test query showing what it drops, and a restriction that audit logs are routed by a separate non-excluded sink.
  • Retention by regulation. A financial team needed seven years of administrative records. They routed cloudaudit logs to a Cloud Storage bucket with a locked retention policy, kept 400 days searchable in _Required, and kept 12 months searchable in a custom bucket with Log Analytics. Each layer had a purpose and cost.
  • Regional bucket for residency. A business unit with a data-residency rule created every bucket in a single region and used gcp.resourceLocations (Hour 3) to prevent other regions. The bucket location was reviewed before the first entry was routed, because it cannot be changed.

Practices

  • Leave the _Required bucket alone and route a copy of audit logs to a project that only the logging team administers.
  • Set the _Default retention deliberately. Thirty days is cheap but may be shorter than your incident-detection window.
  • Prefer inclusion filters on logName, resource.type and severity. Broad filters like an empty one multiply ingestion.
  • Test every filter in Logs Explorer before saving it in a sink, and keep the tested query in the pull request.
  • Use a naming standard for sinks and buckets such as sink-audit-to-central and bkt-audit-365.
  • Alert on changes to sinks and exclusions (Module 4).

Security notes

Writer identity is a data path. A sink to Cloud Storage, BigQuery or Pub/Sub gives the writer identity write access to that destination. Grant the narrowest role, on the destination only, with an IAM condition where available, and never reuse a broad role such as roles/editor for it.
Exported logs carry sensitive data. A BigQuery dataset or Pub/Sub topic that receives audit logs needs the same access control as the logs, or stricter. Restrict access to groups, and use CMEK where policy requires it.

Symptoms and first checks

SymptomLikely causeFirst check
Entries do not appear in the destinationWriter identity lacks permission, or the filter does not matchgcloud logging sinks describe SINK --format="value(writerIdentity)", then check IAM on the destination
Entries missing from _Default that you expectAn exclusion filter, or the entry is in _Required (audit activity)gcloud logging sinks describe _Default and read the exclusions
Invalid destination when creating a sinkWrong prefix or missing location in the bucket pathCompare with logging.googleapis.com/projects/PROJECT_ID/locations/LOCATION/buckets/BUCKET_ID
Bucket cannot be reused after deleteThe bucket is in the pending-deletion stategcloud logging buckets list --location=global and look at LIFECYCLE_STATE
Cannot shorten or change a bucketThe bucket is locked, or you changed the location (not possible)gcloud logging buckets describe BUCKET --location=LOCATION (check locked)
Ingestion cost rises after creating a sinkBroad filter copies a high-volume log a second timeLogs Explorer with the sink filter; check volume in the Logs Storage page
BigQuery sink creates no tablesDataset in a different region than expected, or missing roles/bigquery.dataEditorRead the sink error entries; check dataset IAM

Triage order

  1. Is the entry produced at all? Search in Logs Explorer with a broad filter and a short window.
  2. Which sinks exist at this resource and at its parents (gcloud logging sinks list with --folder or --organization)?
  3. Does the inclusion filter match the entry? Test the filter in Logs Explorer.
  4. Does an exclusion remove it? Read the sink's exclusions.
  5. Can the writer identity write at the destination? Check IAM and the destination's own rules (retention policy, dataset location, organization policy).

Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.

Official reading: Routing and storage overview · Configure and manage sinks · Configure log buckets.

or score ≥ 70% on the quiz

Module 3 · Centralized logging architecture

14–21 · Aggregated organization sinks, a dedicated logging project, writer grants, CMEK, Log Analytics and cost
Aggregated sinks--include-childrenWriter identityCMEKLog Analytics7 min
Learning objectives
  • Design a central logging project and an organization-level aggregated sink that collects audit logs from every project.
  • Grant the sink's writer identity the narrowest role on the destination and protect the destination with CMEK and restricted access.
  • Explain Log Analytics and the main drivers of logging cost, and say what to do when there is no organization.

The short answer

A centralized logging architecture collects the logs that matter (above all audit logs) from every project into a small number of well-protected destinations, controlled by a platform or security team. The building block is an aggregated sink (聚合接收器): a sink created on the organization or on a folder with --include-children, so that logs from all projects below it follow one rule. The destination is usually a log bucket in a dedicated logging project.

What: the pieces

PieceRole
Organization sink with --include-childrenOne routing rule for all current and future projects. New projects are covered automatically.
Folder sink with --include-childrenThe same, limited to a subtree (for example only production), with its own retention or destination.
Logging project (for example prj-logging)Holds the central buckets, in the platform folder. Only the platform and security groups administer it.
Central log bucketsOne bucket per purpose, such as org-audit (audit, long retention) and org-security (detections). Keep the bucket count small.
Writer identity grantThe sink's service account receives roles/logging.bucketWriter on the destination.
Log views and IAMDecide who reads what: roles/logging.viewAccessor on a view, roles/logging.privateLogViewer for Data Access logs.
CMEKCloud KMS key that encrypts a bucket when policy requires customer-controlled keys.
Log AnalyticsSQL over a bucket and optional linked BigQuery dataset.

How it works internally

  1. You create the sink on the organization: gcloud logging sinks create NAME DESTINATION --organization=ORG_ID --include-children --log-filter=....
  2. The service creates a unique writer identity for this sink, a service account such as o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com. You read it with sinks describe.
  3. You grant that identity roles/logging.bucketWriter on the logging project. Until you do, the destination rejects the writes.
  4. From then on, every matching entry in any project below the organization is also written to the central bucket. The original copy stays in the producing project's _Required or _Default bucket, because the aggregated sink is non-intercepting by default.
  5. With the --intercept-children option (check gcloud logging sinks create --help) an aggregated sink can instead stop children from storing matching entries locally. Use it only with a deliberate design, because it changes what project owners can see and you can lose evidence if the sink breaks.

Why it is needed

  • Tamper resistance. A project owner can delete a project and its logs. A central copy in another project survives.
  • One view of the organization. Security investigates across projects with one query, instead of visiting dozens of projects.
  • Consistency. A rule set once at the organization applies to new projects without a ticket.
  • Separation of duties. The team that produces logs does not administer the team that retains them.

When to use which scope

SituationDesign
You have an organization and a platform teamOrganization sink to a central bucket; separate folder sinks if production needs a different retention or destination
One regulated folder (for example regulated data)Folder sink with --include-children to a dedicated bucket in a dedicated region, plus the organization sink for the general case
No organization (a personal or small account)A project-level sink in each project to a bucket in one logging project; the same grant steps apply, but there is no automatic coverage of new projects
You need a SIEMOrganization sink to a Pub/Sub topic in the logging project with a subscriber for the SIEM, in addition to the bucket

Log Analytics

If you create the bucket with analytics enabled (or upgrade an existing bucket; check gcloud logging buckets create --help and update --help for --enable-analytics in your SDK version), you can run SQL in Logs Explorer, Log Analytics. You can create a linked dataset (gcloud logging links create) so BigQuery sees the bucket's data without a copy and without a second Logging ingestion. Analysts can join audit logs with other tables. This does not change retention, and it does not make the data free: ingestion is still billed once, and queries have their own cost model. Use it where analysis, not only search, is required.

CMEK for log buckets

Organizations with a key-control requirement encrypt buckets with a Cloud KMS key (Hour 3). The Cloud Logging service agent needs roles/cloudkms.cryptoKeyEncrypterDecrypter on the key. You can set a default key for the organization (gcloud logging settings update --organization=ORG_ID --kms-key-name=KEY; check the help for the flags in your SDK version) so that new buckets use it. If the key is disabled or destroyed, the logs become unreadable, so treat the key as part of the evidence chain: rotate, do not delete, and alert on key changes.

Cost drivers

DriverWhat increases itControl
Ingestion into bucketsHigh-volume logs copied to extra buckets, Data Access logs, application DEBUG logsNarrow inclusion filters, exclusions, enable only needed Data Access types
RetentionLong retention on high-volume bucketsLong retention only for the audit bucket; short for operational logs
Log Analytics and BigQueryRepeated large queries; BigQuery storage of exportsPartitioned tables, query filters on time, a reservation or a budget alert
Cross-region transferDestination in a different region from the sourceCheck regional egress rules before choosing locations

The principle: every copy is a cost and every copy is a risk. Route a copy only when someone has a use for it.

Common misunderstandings

"An org sink also changes what each project stores." By default it does not. The projects keep their own copies; the sink adds a central copy. Interception is a separate, deliberate setting.
"The sink needs a role on the organization." The writer identity needs a write role on the destination, not on the organization. Creating the sink needs roles/logging.configWriter on the organization.
"Central means one giant bucket." Mixed purposes make access control and retention impossible. Use a few buckets by purpose, and use log views for fine-grained read access.
Organization: example.com sink org-audit · --include-children Folder: platform prj-logging · prj-net-hub · prj-kms Folder: production prj-app-a · prj-app-b · prj-app-c prj-app-a prj-app-b Each project keeps its own _Required and _Default buckets prj-logging (only platform + security administer) Bucket: org-audit 400 days · CMEK · Log Analytics Bucket: org-security detections · 90 days Pub/Sub topic: siem-feed to the SIEM · subscriber aggregated copy via writer identity Access model Writer identity: roles/logging.bucketWriter (destination only) Security analysts: roles/logging.viewAccessor on views Application teams: no access to prj-logging Admins: break-glass group only, changes alerted

Figure 1. One organization sink collects audit logs from every project into the logging project. Producers keep their local copy; the central copy is protected by a separate trust boundary.

1. Create sink --organization --include-children 2. Read writer sinks describe 3. Grant role bucketWriter on prj-logging 4. Verify read from bucket Step 3 is the one people forget. The sink exists and looks healthy, but no entries arrive. Step 4 reads from the destination, not from the source project, to prove the whole path works. For a CMEK bucket, also grant the Cloud Logging service agent encrypt and decrypt on the key. Repeat the four steps for every additional sink, folder sink or Pub/Sub destination. Put all four steps in Terraform so a recreated sink gets its grant again.

Figure 2. The four-step sequence for any cross-project sink. A new writer identity is created whenever a sink is recreated, so the grant must be part of the same code.

In the first diagram, follow the arrow from the application project: the producer never talks to the logging project directly. The writer identity does, which is why the application team needs no access there. In the second, note that verification reads from the destination.

The animation follows one audit entry from an application project to the central bucket. Pay attention to the fourth step: the IAM check on the logging project is the control that makes the central copy tamper-resistant, and the writer identity is the only principal that is allowed in.

Organization-level commands need an organization and roles/logging.configWriter on it. Creating a sink and a bucket is free; ingestion into the central bucket is billed by volume. IDs in the expected output are illustrative. Without an organization, use the project-level form shown in the Lab tab.

gcloud logging buckets create in the logging project

Purpose. Creates the central audit bucket with long retention and Log Analytics enabled.

gcloud logging buckets create org-audit \
  --location=global \
  --retention-days=400 \
  --enable-analytics \
  --description="Central audit logs" \
  --project=LOG_PROJECT_ID
Created bucket [org-audit].
analyticsEnabled: true
lifecycleState: ACTIVE
name: projects/lz-logging/locations/global/buckets/org-audit
retentionDays: 400

Flags. --enable-analytics turns on Log Analytics (check gcloud logging buckets create --help for your SDK version). Use a region instead of global if residency requires it; the location cannot be changed. Cost: the bucket is free to create; ingestion and retention are billed.

gcloud logging sinks create --organization --include-children

Purpose. Creates the aggregated sink for all audit logs of the organization.

gcloud logging sinks create org-audit-sink \
  logging.googleapis.com/projects/LOG_PROJECT_ID/locations/global/buckets/org-audit \
  --organization=ORG_ID \
  --include-children \
  --log-filter='logName:"logs/cloudaudit.googleapis.com"' \
  --description="All audit logs to the central bucket"
Created [https://logging.googleapis.com/v2/organizations/123456789012/sinks/org-audit-sink].
Please remember to grant `serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com` the Logs Bucket Writer role on the destination.

Flags. --organization chooses the scope (use --folder=FOLDER_ID for a folder). --include-children includes every descendant. The filter limits the copy to audit logs, which controls cost. Common errors. PERMISSION_DENIED means you lack logging.sinks.create on the organization. Invalid destination means the project, location or bucket ID is wrong. Cost: free to create.

gcloud logging sinks describe (read the writer identity)

gcloud logging sinks describe org-audit-sink --organization=ORG_ID --format="value(writerIdentity)"
serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com

Purpose. Gives you the exact principal to authorise. Do not guess it; it is unique per sink and changes if you delete and recreate the sink. Cost: free.

gcloud projects add-iam-policy-binding (grant the writer)

Purpose. Lets the writer identity store entries in the logging project, restricted by a condition to one bucket.

gcloud projects add-iam-policy-binding LOG_PROJECT_ID \
  --member="serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com" \
  --role="roles/logging.bucketWriter" \
  --condition='expression=resource.name.endsWith("locations/global/buckets/org-audit"),title=org-audit-writer-only'
Updated IAM policy for project [lz-logging].
bindings:
- condition:
    expression: resource.name.endsWith("locations/global/buckets/org-audit")
    title: org-audit-writer-only
  members:
  - serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com
  role: roles/logging.bucketWriter
etag: BwY…
version: 3

Flags. --condition adds an IAM Condition so the identity can write only to that bucket. Conditional bindings require policy version 3; gcloud handles this in current versions. Cost: free. Production use: in Terraform, use google_project_iam_member with a condition block, or google_logging_organization_sink outputs writer_identity.

gcloud logging links create (link a BigQuery dataset)

Purpose. Exposes the Log Analytics bucket as a read-only BigQuery dataset so analysts can query with their existing BigQuery tools.

gcloud logging links create audit_link \
  --bucket=org-audit --location=global --project=LOG_PROJECT_ID

Flags. The link name becomes the dataset name; use letters, digits and underscores. Check gcloud logging links create --help for the flags in your SDK version. Cost: no extra ingestion; queries are billed by BigQuery.

gcloud logging settings describe (organization CMEK service agent)

gcloud logging settings describe --organization=ORG_ID
kmsServiceAccountId: service-org-123456789012@gcp-sa-logging.iam.gserviceaccount.com
loggingServiceAccountId: service-org-123456789012@gcp-sa-logging.iam.gserviceaccount.com
name: organizations/123456789012/settings

Purpose. Shows the service account that needs roles/cloudkms.cryptoKeyEncrypterDecrypter on the CMEK key. Output fields may differ by SDK version. Cost: free.

Production use. Treat the sink, the bucket, the grant and the CMEK permission as one module in Terraform, with an output that lists the destination and the writer identity. Review it like firewall code.

Lab: a central audit bucket with a project-level sink (about 20 minutes, low cost)

Goal. Build a miniature central logging design: one logging project, one bucket, one sink from another project, an explicit writer grant, and proof that an event arrives. If you have an organization, an extra step shows the organization form without changing the lab's cost. IDs in the expected output are illustrative.

Prerequisites. Two sandbox projects: LOG_PROJECT_ID (the logging project) and APP_PROJECT_ID (a producer), both with a billing account linked and a budget set first. You need roles/logging.configWriter on both, roles/resourcemanager.projectIamAdmin on LOG_PROJECT_ID, and roles/logging.viewer. No organization is needed; budgets alert and do not cap spend.

  1. Create the central bucket in the logging project.
    gcloud logging buckets create central-audit --location=global --retention-days=30 --project=LOG_PROJECT_ID
    Verify: gcloud logging buckets list --project=LOG_PROJECT_ID shows central-audit with 30 days.
  2. Create a project-level sink in the producer project that points at the central bucket.
    gcloud logging sinks create central-audit-sink \
      logging.googleapis.com/projects/LOG_PROJECT_ID/locations/global/buckets/central-audit \
      --log-filter='logName:"logs/cloudaudit.googleapis.com%2Factivity"' --project=APP_PROJECT_ID
  3. Read the writer identity and store it in a shell variable.
    WRITER=$(gcloud logging sinks describe central-audit-sink --project=APP_PROJECT_ID --format="value(writerIdentity)")
    echo "$WRITER"
    Verify: the value starts with serviceAccount: and ends with @gcp-sa-logging.iam.gserviceaccount.com.
  4. Test first without the grant: generate an event in the producer and look in the central bucket after two minutes.
    gcloud iam service-accounts create central-demo --project=APP_PROJECT_ID
    gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount"' \
      --bucket=central-audit --location=global --view=_AllLogs --project=LOG_PROJECT_ID --freshness=1h --limit=1
    Expected: no output, because the writer identity is not yet authorised. This shows the most common failure on purpose.
  5. Grant the writer identity the bucket writer role on the logging project.
    gcloud projects add-iam-policy-binding LOG_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter"
  6. Generate a second event and read again.
    gcloud iam service-accounts create central-demo-2 --project=APP_PROJECT_ID
    gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount"' \
      --bucket=central-audit --location=global --view=_AllLogs --project=LOG_PROJECT_ID --freshness=1h --limit=2 \
      --format="value(timestamp,protoPayload.resourceName)"
  7. If you have an organization (optional, read-only): list organization sinks with gcloud logging sinks list --organization=ORG_ID and describe any existing aggregated sink to see its includeChildren value. Do not create an organization sink in a shared organization without approval.

Expected result. Step 4 prints nothing. Step 6 prints one line for central-demo-2 (and entries written after the grant). The first event, created before the grant, may be missing from the central bucket, which is the effect of the missing permission.

2026-11-25T11:20:08.771Z  projects/lz-app-0002/serviceAccounts/central-demo-2@lz-app-0002.iam.gserviceaccount.com

Verification. Describe the sink and confirm the destination, then check IAM: gcloud projects get-iam-policy LOG_PROJECT_ID --flatten="bindings[].members" --filter="bindings.role=roles/logging.bucketWriter" --format="value(bindings.members)" must list the writer identity.

Cost. Low (usually well under a few USD per day for this lab). A handful of audit entries is copied into one bucket.

Cleanup.

gcloud projects remove-iam-policy-binding LOG_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter"
gcloud logging sinks delete central-audit-sink --project=APP_PROJECT_ID --quiet
gcloud logging buckets delete central-audit --location=global --project=LOG_PROJECT_ID --quiet
gcloud iam service-accounts delete central-demo@APP_PROJECT_ID.iam.gserviceaccount.com --project=APP_PROJECT_ID --quiet
gcloud iam service-accounts delete central-demo-2@APP_PROJECT_ID.iam.gserviceaccount.com --project=APP_PROJECT_ID --quiet

Real cases (typical patterns)

  • The logging project that was an application project. A team reused an existing project as the central destination. Its owners could delete the bucket, and a developer with roles/editor changed retention. The rebuilt design used a new project in the platform folder, no basic roles, and an organization policy and alert on changes to its IAM policy.
  • One sink for everything. A first design routed every log of every project into one bucket with an empty filter. Cost grew with every new workload and nobody could find anything. The rebuilt design routed audit logs to one bucket, security product findings to another, and left application logs in each project's _Default with a 30-day retention; application teams used Logs Explorer in their own projects.
  • Key rotation and unreadable logs. A key for CMEK was scheduled for destruction during a cleanup because it looked unused. The bucket's logs would have become unreadable. The fix was a label and an alert on key lifecycle events, an organization policy limiting who can destroy keys, and a runbook that links the key to the evidence retention policy.

Practices

  • Create a dedicated logging project in the platform folder, linked to a billing account that the platform team owns.
  • Use one organization sink for audit logs and separate sinks by purpose. Keep the filters in code and tested.
  • Grant the writer identity the narrowest role on the destination, with a condition limiting it to one bucket.
  • Give readers views and group-based roles, not project-wide viewer roles.
  • Create the destination bucket and the grant before the sink in the pipeline, and verify with a canary event after every change.
  • Alert on changes to sinks, buckets, retention, exclusions and CMEK keys of the logging project.

Security notes

Do not make the logging project a general workload project. Every extra principal with write or admin access is a way to alter evidence. Keep it nearly empty, and protect it with Organization Policy and, in regulated cases, a VPC Service Controls perimeter (Hour 3) that includes Cloud Logging.
Aggregated sinks see everything below them. Treat the filter as a data decision: Data Access logs can carry object names and query text. Include only what the security team needs, and document the legal basis for collecting it.

Symptoms and first checks

SymptomLikely causeFirst check
No entries in the central bucketWriter identity has no roles/logging.bucketWriter on the destinationsinks describe for the identity; get-iam-policy on the logging project
Entries only from some projectsSink created without --include-children, or the project is outside the folder or organization scopegcloud logging sinks describe NAME --organization=ORG_ID (look at includeChildren)
Writes stopped after a sink was recreatedA new sink has a new writer identity that was never grantedCompare the identity in describe with the member in the IAM policy
Logs unreadable or write errors on a CMEK bucketKey disabled, destroyed or service agent lacks encrypt and decryptKey state in Cloud KMS; gcloud logging settings describe for the service agent
Ingestion cost jumped after the org sinkFilter too broad or Data Access enabled widelyLogs Storage page: volume by log name; test the filter in Logs Explorer
Readers see no entries in the central bucketNo view access, or Data Access logs need privateLogViewerIAM roles on the bucket or view for the reader group
Sink creation deniedMissing roles/logging.configWriter at the organization or an organization policy blocks itgcloud organizations get-iam-policy ORG_ID filtered to your group

Triage order

  1. Confirm the sink scope and filter: sinks describe with the right flag.
  2. Confirm the writer identity and its role on the destination.
  3. Confirm the destination exists, is active and is in the expected location.
  4. Generate a canary event in a child project and read it from the destination.
  5. If CMEK is on, check the key and its permissions.

Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.

Official reading: Aggregated sinks · Security foundations: operations · Log Analytics.

or score ≥ 70% on the quiz

Module 4 · Cloud Monitoring

21–28 · Metrics scopes, alerting policies, notification channels, uptime checks, and alerts on audit events and budgets
Metrics scopeAlerting policiesNotification channelsUptime checksLog-based alerts7 min
Learning objectives
  • Explain metrics scopes, metrics, alerting policies and notification channels, and how an incident is opened and closed.
  • Create a notification channel and an alerting policy, including a log-based alert on an audit event such as an IAM policy change.
  • Design a minimal landing-zone alert set that covers platform changes, budgets and the availability of one service.

The short answer

Cloud Monitoring (云监控) collects metrics, shows them in dashboards and raises alerts. In a landing zone it has two jobs. The first is platform health: availability of shared services (NAT, VPN tunnels, DNS, load balancers). The second is platform governance: being told when something that should rarely change does change (IAM, firewall, sinks, organization policy) or when spend crosses a threshold. Logs give the evidence; monitoring tells people to look at it.

What: the building blocks

ConceptWhat it is
MetricA time series of numbers, such as compute.googleapis.com/instance/cpu/utilization. Google Cloud services write system metrics automatically at no extra charge; custom and external metrics are billed.
Monitored resourceThe thing a metric describes (VM instance, load balancer, project). Labels split a metric into series.
Metrics scopeThe set of projects that one scoping project can view and alert on. Every project is its own scoping project by default.
DashboardA saved set of charts for a team or a service.
Alerting policyConditions + notification channels + documentation. Conditions can be metric threshold, metric absence, forecast, or log-match.
Notification channelEmail, SMS, Slack, mobile app, webhook, Pub/Sub, or an incident tool such as PagerDuty.
IncidentOpened when a condition is met, closed when it clears (or after an auto-close time for log alerts).
Uptime checkSynthetic probes of an HTTP(S), TCP or private endpoint from multiple regions.
Log-based metricA metric computed from log entries (counter or distribution), usable in alerts and dashboards.
SLOA service-level objective with an error budget, used for burn-rate alerting on important services.

How it works internally

  1. Services and agents write time-series points to Cloud Monitoring (Google Cloud services automatically; VMs via the Ops Agent; applications via client libraries or Managed Service for Prometheus).
  2. An alerting policy is evaluated continuously against these points. A threshold condition checks an aligned value against a limit for a duration. An absence condition checks for missing data. A log-match condition watches the log stream for entries that match a filter.
  3. When a condition is met, an incident opens and the policy sends a notification to every attached channel. Documentation text in the policy is included, which is where the runbook link belongs.
  4. When the condition stops being met, the incident closes and, if configured, a "resolved" notification is sent. Log-match incidents close after an auto-close period.

The metrics-scope design for a landing zone

A common pattern uses one monitoring project (for example prj-monitoring in the platform folder) as the scoping project for shared platform projects, and a scoping project per environment or business unit for application projects. This keeps alert ownership clear. Add monitored projects with the console (Monitoring, Settings, Metrics Scope, Add projects) or with Terraform (google_monitoring_monitored_project). Check the current quota on the number of projects in one scope before you design around it. Grant roles/monitoring.viewer or roles/monitoring.editor on the scoping project, and use roles/monitoring.alertPolicyEditor and roles/monitoring.notificationChannelEditor for people who manage alerts only.

Alerts every landing zone needs

SignalTypeExample filter or conditionWho is notified
IAM policy changedLog-basedprotoPayload.methodName:"SetIamPolicy" in the activity logSecurity
Service account key createdLog-basedprotoPayload.methodName="google.iam.admin.v1.CreateServiceAccountKey"Security
Organization policy changedLog-basedprotoPayload.serviceName="orgpolicy.googleapis.com" (activity log)Platform
Firewall or route changedLog-basedprotoPayload.methodName:("compute.firewalls.insert" OR "compute.firewalls.patch" OR "compute.firewalls.delete")Network
Log sink or exclusion changedLog-basedprotoPayload.methodName:("UpdateSink" OR "DeleteSink" OR "UpdateExclusion")Platform and security
Budget threshold reachedBudget notification (email or Pub/Sub)Thresholds on actual and forecasted spend (Module 5)Cost owner
Shared service availabilityUptime check or metric thresholdProbe failures from two or more regionsOn-call
VPN tunnel down, NAT dropsMetric threshold or absenceTunnel status, dropped_sent_packets_countNetwork on-call
Log ingestion spikeMetric thresholdLogging bytes ingested per day vs a limitPlatform

Keep the set small and meaningful. An alert that fires daily teaches the team to ignore alerts.

When to use what

QuestionUse
Is the service up from the outside?Uptime check with an alert
Is a resource running hot or failing?Metric threshold alert, dashboards
Did a job stop reporting?Metric absence alert
Did someone change something critical?Log-based alert on the audit entry
Are we spending too much?Budget alerts (not a cap), billing export analysis
Is the user experience degrading?SLO with burn-rate alerts

What it is confused with

Often confused withDifference
Cloud LoggingLogging stores events. Monitoring stores numeric time series and sends alerts. They meet in log-based metrics and log-based alerts.
Security Command CenterSCC detects vulnerabilities and threats and creates findings. Monitoring alerts on metrics and logs you define.
Budget alertsBudgets belong to Cloud Billing and use their own notifications; they can use Monitoring channels but are not Monitoring alerting policies.
Error Reporting, Cloud Trace, ProfilerApplication diagnostics tools. They help find causes; they do not replace platform alerts.

Common misunderstandings

"I created the policy, so I am covered." A policy with no channel, an unverified email, or a channel for a person who left raises incidents that no one sees. Test every channel with a real notification.
"Monitoring is free." System metrics from Google Cloud services are not billed, but custom metrics, external metrics, Managed Service for Prometheus samples and some log-based metrics can be. Check the pricing page before you create high-cardinality metrics.
"Alerts will catch everything." A metric condition cannot detect an event that produces no metric. Use log-based alerts for audit events, and absence conditions for jobs that must report.
System metrics VPN, NAT, LB, VM, quotas Audit and platform logs log-based alert or metric Uptime checks probes from several regions Billing budgets thresholds on spend Alerting policy conditions · documentation rate limit · auto-close in the scoping project Notification channels email · Slack · webhook Pub/Sub · incident tool verified, tested Budget alerts use their own rules and can reuse the same channels Dashboards and the metrics scope sit beside this path: they show the same data to people.

Figure 1. Four sources, one alerting model. The alerting policy decides when something is an incident; the channel decides who hears about it.

prj-monitoring scoping project · dashboards · alerts prj-net-hub prj-app-a prj-app-b prj-logging Monitored projects keep their own metrics. The scoping project reads them. Alert ownership follows the scoping project, so one team owns each scope.

Figure 2. A metrics scope. The scoping project holds alerting policies and channels; monitored projects only produce metrics.

Read the first diagram from the sources on the left: budgets are the only source that does not pass through the policy, and that is why you test them separately. In the second diagram, the arrow direction shows read access: the scoping project reads the monitored projects, and not the other way round.

The animation follows one platform event, an IAM policy change, from the audit entry to a person who is notified. Step 3 is the one that prevents alert storms: the notification rate limit. Step 6 shows that incidents close without manual work.

Alerting commands are in the alpha or beta release tracks in many SDK versions, and the console and Terraform are the stable way to manage them. Check gcloud alpha monitoring --help and gcloud beta monitoring --help for the commands and flags in your SDK version. Creating channels and policies is free; custom metrics and some log-based metrics can be billed. IDs in the expected output are illustrative.

gcloud logging metrics create (log-based metric)

Purpose. Counts audit entries that match a filter, so you can chart or alert on them.

gcloud logging metrics create iam-policy-changes \
  --description="Count of SetIamPolicy calls" \
  --log-filter='logName:"cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName:"SetIamPolicy"' \
  --project=PROJECT_ID
Created [iam-policy-changes].
description: Count of SetIamPolicy calls
filter: logName:"cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName:"SetIamPolicy"
name: iam-policy-changes

Flags. --log-filter is the same Logging query language as for sinks. The metric counts from creation onward; it does not back-fill. The metric is visible as logging.googleapis.com/user/iam-policy-changes. Check gcloud logging metrics create --help for distribution metrics and labels. Cost: the metric is a user-defined metric; check the pricing page for chargeable metrics, and keep the label cardinality low.

gcloud logging metrics list and describe

gcloud logging metrics list --project=PROJECT_ID
gcloud logging metrics describe iam-policy-changes --project=PROJECT_ID

Purpose. Confirms the filter that was saved. Cost: free.

gcloud alpha monitoring channels create (notification channel)

Purpose. Creates an email channel. Email channels must be verified by the recipient in the console before delivery is reliable.

gcloud alpha monitoring channels create \
  --display-name="Platform ops email" \
  --type=email \
  --channel-labels=email_address=GROUP_EMAIL \
  --project=PROJECT_ID
Created notification channel [projects/lz-monitoring/notificationChannels/1234567890123456789].

Flags. --type selects the channel kind (email, slack, pubsub, webhook_tokenauth and others); --channel-labels carries the type-specific labels. Slack channels need an OAuth step in the console. Use a group address, not a person, so rotations do not break delivery. Cost: free (SMS and some integrations depend on the provider). If the command is not found in your SDK version, create the channel in the console under Monitoring, Alerting, Edit notification channels.

gcloud alpha monitoring channels list

gcloud alpha monitoring channels list --project=PROJECT_ID --format="table(name,displayName,type,enabled)"
NAME                                                     DISPLAY_NAME       TYPE   ENABLED
projects/lz-monitoring/notificationChannels/1234567890123456789  Platform ops email  email  True

Purpose. Gives you the channel resource name you place in the policy file. Cost: free.

gcloud alpha monitoring policies create --policy-from-file

Purpose. Creates a log-based alert that fires whenever an IAM policy change is written. Save the JSON as iam-alert.json, replacing PROJECT_ID and the channel ID.

{
  "displayName": "IAM policy changed",
  "combiner": "OR",
  "conditions": [
    {
      "displayName": "SetIamPolicy audit entry",
      "conditionMatchedLog": {
        "filter": "logName:\"cloudaudit.googleapis.com%2Factivity\" AND protoPayload.methodName:\"SetIamPolicy\""
      }
    }
  ],
  "alertStrategy": {
    "notificationRateLimit": { "period": "300s" },
    "autoClose": "604800s"
  },
  "notificationChannels": [
    "projects/PROJECT_ID/notificationChannels/CHANNEL_ID"
  ],
  "documentation": {
    "content": "An IAM policy changed. Find the principal and the target with: gcloud logging read 'protoPayload.methodName:\"SetIamPolicy\"' --freshness=1h. Check the change ticket.",
    "mimeType": "text/markdown"
  }
}
gcloud alpha monitoring policies create --policy-from-file=iam-alert.json --project=PROJECT_ID
Created alert policy [projects/lz-monitoring/alertPolicies/9876543210987654321].

Flags. notificationRateLimit is required for log-match conditions and limits the notifications to one per period. autoClose closes the incident after the period with no new matches. Common errors. INVALID_ARGUMENT usually means a JSON typo, a missing rate limit, or a channel name from another project. The policy file shape can change between API versions; the console's View as JSON on an existing policy is the reference. Cost: free.

gcloud alpha monitoring policies list

gcloud alpha monitoring policies list --project=PROJECT_ID --format="table(displayName,enabled,combiner)"

Purpose. Lists policies so you can find and review them. Cost: free.

Uptime checks (console flow and Terraform)

Purpose. Probe an HTTPS endpoint from multiple regions. In the console: Monitoring, Uptime checks, Create uptime check; choose protocol HTTPS, the resource (URL or instance), the path, the frequency, the regions and the response validation; then use Create alert on the same page to attach a notification channel. In code, use google_monitoring_uptime_check_config with google_monitoring_alert_policy. Private endpoints need a private check with a Service Directory or VPC-based configuration; check the current documentation. Uptime checks are billed by the number of executions after a free allowance, so choose frequency and regions deliberately.

Production use. Store alert policies and channels in Terraform, review them as code, and write the runbook link into the policy documentation, so the on-call engineer sees what to do in the notification itself.

Lab: alert on an IAM change (about 15 minutes, free to low cost)

Goal. Create an email notification channel and a log-based alert policy for SetIamPolicy, trigger it with a harmless IAM change, and confirm that the incident opens and the email arrives. IDs in the expected output are illustrative.

Prerequisites. A sandbox project (PROJECT_ID), roles/monitoring.alertPolicyEditor and roles/monitoring.notificationChannelEditor (or roles/monitoring.editor), roles/logging.viewer, and an email address you can read. Budget set first (budgets alert and do not cap spend). No organization needed.

  1. Create the notification channel. If the alpha command is not available, use the console.
    gcloud alpha monitoring channels create --display-name="Lab email" --type=email --channel-labels=email_address=YOUR_EMAIL --project=PROJECT_ID
    gcloud alpha monitoring channels list --project=PROJECT_ID --format="value(name)"
    Verify: the second command prints projects/PROJECT_ID/notificationChannels/NUMBER. Copy it. Check your mailbox for a verification email and accept it if one arrives.
  2. Save the JSON policy from the Commands tab as iam-alert.json and replace the channel line with the value from step 1. Keep "period": "300s".
  3. Create the policy.
    gcloud alpha monitoring policies create --policy-from-file=iam-alert.json --project=PROJECT_ID
    Verify: gcloud alpha monitoring policies list --project=PROJECT_ID --format="table(displayName,enabled)" shows IAM policy changed with True.
  4. Trigger the alert with a harmless, reversible change: create a service account and bind a harmless role on it to yourself, which writes SetIamPolicy.
    gcloud iam service-accounts create alert-demo --project=PROJECT_ID
    gcloud iam service-accounts add-iam-policy-binding alert-demo@PROJECT_ID.iam.gserviceaccount.com \
      --member="user:YOUR_EMAIL" --role="roles/iam.serviceAccountViewer" --project=PROJECT_ID
  5. Confirm the audit entry exists.
    gcloud logging read 'protoPayload.methodName:"SetIamPolicy" AND protoPayload.resourceName:"alert-demo"' \
      --project=PROJECT_ID --freshness=1h --limit=1 --format="value(timestamp,protoPayload.authenticationInfo.principalEmail)"
  6. Open Monitoring, Alerting in the console. Within a few minutes an incident named after the policy should appear, and an email should arrive. Open the incident and read the documentation text.
  7. Write down the delay between the change and the email. This is your detection time for this signal.

Expected result. One open incident for IAM policy changed and one email. If the entry exists but there is no incident, the policy filter does not match; compare it with the entry's methodName.

2026-11-25T12:41:07.220Z  ana@example.com

Verification. gcloud alpha monitoring policies describe POLICY_NAME --project=PROJECT_ID shows the condition and the channel. In the console, the policy page lists the channel as Verified.

Cost. Free for the channel and the policy. Log-match alerts do not create custom metric charges, and the audit entries are not billed. Total: free to low.

Cleanup.

gcloud alpha monitoring policies delete POLICY_NAME --project=PROJECT_ID --quiet
gcloud alpha monitoring channels delete CHANNEL_NAME --project=PROJECT_ID --quiet
gcloud iam service-accounts delete alert-demo@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet

Use the full names from the list outputs for POLICY_NAME and CHANNEL_NAME. Closing the open incident in the console is optional; it auto-closes.

Real cases (typical patterns)

  • The silent policy change. An organization-level IAM change granted a broad role to a contractor group. There was no alert, and the change was found in a quarterly review. After the incident the security team added log-based alerts for IAM, organization policy, service account key and sink changes, notification to a team channel, and a rule that each alert has an owner and a documented response.
  • Alert fatigue. A platform team created dozens of CPU alerts for every project. Pages arrived at night and were ignored. The redesign kept a few symptom-based alerts (service unavailable, VPN tunnel down, error budget burning) paged to on-call, and moved the rest to dashboards and daily reports.
  • Budget alert nobody read. A budget notified a former employee. Costs rose for six weeks. The fix was a group email address, a Pub/Sub notification that posts to the team's chat tool, and a quarterly check that every channel still reaches a person.

Practices

  • Create a monitoring project in the platform folder as the scoping project for shared services, and give each environment its own scoping project.
  • Alert on symptoms that need a human (platform changes, outages, burning budgets), not on every metric.
  • Always use group addresses and shared channels; test them quarterly with a real notification.
  • Put a runbook link and the first command to run into the policy documentation.
  • Manage alerts and channels in Terraform, review changes, and alert on changes to the monitoring configuration itself.
  • Define severity levels so the channel matches the urgency (page, chat, email).

Security notes

Webhooks and Pub/Sub carry incident data. Notifications can contain resource names, project IDs and log excerpts. Use authenticated webhooks, restrict the Pub/Sub topic, and never put secrets in the policy documentation.
An attacker who can edit policies can silence them. Restrict roles/monitoring.admin and roles/monitoring.alertPolicyEditor, and alert on changes to alerting policies and channels through a log-based alert.

Symptoms and first checks

SymptomLikely causeFirst check
Incident opened, no notificationNo channel attached, channel unverified, or sent to a mailbox nobody readsPolicy page: Notifications section; channel status
Log-based alert never firesFilter does not match the entry, wrong log name, or entry is at another resourceRun the filter in Logs Explorer against a known event
INVALID_ARGUMENT creating a policy from a fileJSON typo, missing notificationRateLimit for a log condition, channel from another projectValidate JSON, compare with console View as JSON
Dashboard is empty for a projectThe project is not in the metrics scopeMonitoring, Settings, Metrics Scope
Alert fires constantlyThreshold too low, duration too short, or noisy sourceChart the metric for a week and set the threshold above normal
Uptime check shows failures from one region onlyRegional network issue, firewall allowlist missing the probe addressesCheck the uptime check IP ranges against your firewall or Cloud Armor policy
Cost increase after custom metricsHigh-cardinality labels or too many time seriesMetrics Management page: volume by metric

Triage order

  1. Is the signal produced? Check the metric or the log entry directly.
  2. Does the condition match it? Compare the filter, the aligner and the duration with the data.
  3. Is an incident open? Check the Alerting page.
  4. Is a channel attached, enabled and verified, and does it reach a person?
  5. Is the policy in the right scoping project and enabled?

Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.

Official reading: Alerting overview · Metrics scopes · Log-based alerts · Uptime checks.

or score ≥ 70% on the quiz

Module 5 · Cost governance

28–36 · Budgets that alert, billing export to BigQuery, labels for allocation, and commitments
BudgetsBilling exportLabelsCommitments8 min
Learning objectives
  • Create and inspect a Cloud Billing budget with threshold rules, and explain why a budget alerts but does not cap spend.
  • Describe how billing export to BigQuery and resource labels let you allocate cost to teams and environments.
  • Choose between budget alerts, quotas, and automation for the different kinds of cost risk in a landing zone.

The short answer

Cost governance (成本治理) means three things working together: visibility (who spent what, by project, label and SKU), warning (the right people are told before the invoice arrives), and limits (some spend is blocked by quotas, policy or automation). In Google Cloud the first two are provided by Cloud Billing; the third is something you design.

What: the building blocks

Building blockWhat it doesDoes it stop spend?
Billing accountPays for linked projects; holds budgets, exports and permissions (roles/billing.admin, roles/billing.user, roles/billing.viewer)Unlinking a project from it stops paid usage, but that is a drastic manual action
BudgetWatches actual or forecasted spend and notifies at thresholdsNo. Alerts only
Billing export to BigQueryWrites standard usage cost, detailed usage cost and pricing data to datasetsNo. Reporting only
LabelsKey and value pairs on projects and resources, carried into cost rowsNo. Attribution only
QuotasPer-project limits on API calls and resourcesYes, for the quota metric you limit
Organization PolicyBlocks classes of resources, for example gcp.resourceLocations or external IP creationYes, for what the constraint forbids
Commitments (CUD)Lower unit rate in exchange for a one or three year commitmentNo. It lowers cost, and adds a commitment you must use

Why budgets are not caps

Google Cloud bills usage after it happens, so the platform cannot know at the moment of a request whether the budget will be exceeded. A budget is therefore evaluated periodically against reported spend, and billing data can lag by hours. A burst of expensive usage can pass the 100 percent mark before any alert is delivered. For this reason a landing zone treats a budget as an early-warning sensor and builds the actuators separately.

How a budget works internally

  1. Scope. A budget belongs to a billing account. Its scope can be the whole account, or filtered by projects, services, labels, or credits handling.
  2. Amount. A fixed amount for a period (usually a calendar month), or last period's spend.
  3. Threshold rules. A list of percentages of the budget amount, each based on actual spend or forecasted spend. The usual set is 50, 90 and 100 percent actual plus 100 or 110 percent forecast.
  4. Notifications. By default, email to Billing Account Administrators and Users. You can add Cloud Monitoring notification channels (email, chat, webhook) and a Pub/Sub topic that receives a JSON message for automation.

The Pub/Sub message contains fields such as budgetDisplayName, alertThresholdExceeded, costAmount, costIntervalStart, budgetAmount, budgetAmountType and currencyCode. A subscriber can read these and take action, for example posting to a chat room, opening a ticket, or reducing a quota.

Billing export to BigQuery

The export is configured once per billing account in the console (Billing, then Billing export). There are three datasets of interest:

  • Standard usage cost: daily aggregated cost by project, service, SKU, labels and credits. Start here.
  • Detailed usage cost: includes resource-level identifiers (for example a VM instance ID). Larger, and needed for per-resource analysis.
  • Pricing: list price data, useful for comparing your rates with list prices.

The export starts from the day it is enabled and does not back-fill past months, so enable it on day one of a new landing zone. Use a dedicated billing project and dataset, give finance roles/bigquery.dataViewer on the dataset, and keep it in a location that matches your data residency rules.

Labels for allocation

Labels are set on projects and many resources. Cost rows carry labels (resource labels) and project.labels (project labels). A standard landing-zone label set is small: env, cost-center, owner, app, data-class. Labels are lowercase keys, up to 63 characters, with limited characters. Enforce them where projects are created (Hour 7 covers the project factory) and measure the share of cost with no cost-center label as a monthly governance metric.

Commitments and discounts

Committed use discounts (承诺使用折扣) are one or three year commitments. Resource-based commitments reserve vCPU and memory in a region; spend-based commitments commit to an hourly spend on a service family. Sustained use discounts are automatic for some older machine families; check the documentation for your machine type. FinOps practice is: first right-size and remove waste (Recommender reports idle resources), then commit to the stable baseline, and leave the variable part on demand. Do not buy a commitment to hide a workload nobody owns.

When to use which control

RiskBest control
Slow growth nobody noticedBudget with 50, 90, 100 percent actual rules, reviewed monthly with the billing export
Fast runaway (a loop, a crypto-mining intrusion, an open endpoint)Quotas, Organization Policy (no external IPs, allowed locations), forecast alerts, and a Pub/Sub automation for the worst case
Who should pay?Labels and billing export; separate billing accounts only when legal entities differ
Steady baseline workloadCommitted use discount sized from export data
Test projects forgottenSandbox folder with auto-expiry automation and a low budget

What it is confused with

Often confusedDifference
Budget vs quotaA budget notifies about money; a quota enforces a limit on usage of an API or resource.
Billing report vs billing exportThe console report is for browsing; the export is the data you query, join and archive.
Label vs tag (Resource Manager tag)Labels feed billing and filtering. Tags drive IAM conditions and Organization Policy. Module 5 of Hour 1 compares them.
Cloud Billing budget vs Monitoring alertThe budget evaluates billing data; a Monitoring alert evaluates metrics and logs in near real time. Use both.
Common misunderstandings. (1) "The budget will stop us at the limit." It will not. (2) "We can add labels later and the old cost will be tagged." It will not: past rows keep their old labels. (3) "Export is on by default." It is not, and it never back-fills.
Projects usage + labels Cloud Billing account meters and rates usage BigQuery export Budget 50 / 90 / 100 % rules Email and channels people are told Pub/Sub topic JSON for automation Function: quota or ticket the only part that can act Budgets notify. Quotas and Organization Policy limit. Billing data can lag by hours, so a fast loop can pass the threshold before the alert is delivered.

Figure 1. Cost data flow. The budget is a sensor. Only the automation on the right (or a quota) can reduce spend.

What is the cost risk? Slow growth budget + monthly review of the export Fast runaway quotas + org policy + Pub/Sub automation Who pays? labels + billing export + billing structure Steady baseline right-size, then commit (CUD) from export data Most landing zones need all four, owned by different people.

Figure 2. Choose the control from the risk. A single budget does not cover all four rows.

Look at Figure 1 from left to right: usage becomes cost in the billing account, then splits into reporting (export) and warning (budget). The only red box is the one that can change behaviour. In Figure 2, notice that "fast runaway" is the row where a budget alone is not enough.

The player follows one month of usage: metering, export to BigQuery, a threshold crossing, and the Pub/Sub message that automation can act on. Note that the last step is the only one that can change spend, and it is code you wrote, not the budget.

Budget commands need the Cloud Billing Budget API (billingbudgets.googleapis.com) and permission on the billing account (roles/billing.admin or billing.budgets.* permissions). The commands below only create metadata objects, so they are free. Check gcloud billing budgets create --help for the flags in your SDK version.

gcloud billing accounts list

Purpose. Find the billing account ID you will attach the budget to. Free, read-only.

gcloud billing accounts list --format="table(name,displayName,open)"
NAME                              DISPLAY_NAME      OPEN
billingAccounts/0X0X0X-0X0X0X-0X0X0X  Platform billing  True

Flags. --format picks the columns. Common error. An empty list means your identity has no billing role. In production the billing account is managed by a small group with roles/billing.admin, and engineers get roles/billing.viewer or billing.user only on what they need.

gcloud services enable billingbudgets.googleapis.com

Purpose. Enable the Budget API on the project that makes the call (the quota project). Free.

gcloud services enable billingbudgets.googleapis.com --project=PROJECT_ID
Operation "operations/acf.p2-123456789012-example" finished successfully.

Common error. API [billingbudgets.googleapis.com] not enabled on project on the next command. Enable it and retry after a short wait.

gcloud billing budgets create (write, free metadata)

Purpose. Create a monthly budget for one project with actual and forecasted threshold rules. It sends alerts only.

gcloud billing budgets create \
  --billing-account=BILLING_ACCOUNT_ID \
  --display-name="lz-lab-monthly" \
  --budget-amount=50USD \
  --filter-projects=projects/PROJECT_ID \
  --calendar-period=month \
  --threshold-rule=percent=0.5 \
  --threshold-rule=percent=0.9 \
  --threshold-rule=percent=1.0 \
  --threshold-rule=percent=1.0,basis=forecasted-spend
Created budget [billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/11111111-2222-3333-4444-555555555555].

Flags. --budget-amount=50USD sets a specified amount (use --last-period-amount to base it on the previous period instead). --filter-projects restricts the scope; without a filter the budget covers the whole billing account. --calendar-period=month resets monthly. Each --threshold-rule is a fraction of the amount; basis=forecasted-spend uses the forecast instead of actual spend. The amount in a lab should be small and in the billing account currency.

Common errors. PERMISSION_DENIED: you need budget permissions on the billing account, not only on the project. currency mismatch: the amount currency must match the billing account currency.

Cost. Free. Production use. Budgets are created by Terraform (google_billing_budget) in the project factory, one per project or per team, with a Pub/Sub topic and Monitoring channels attached.

gcloud billing budgets create with notifications (write, free metadata)

Purpose. Add a Pub/Sub topic so that automation receives the JSON message, and a Monitoring notification channel so that people receive alerts outside the default billing email recipients.

gcloud billing budgets create \
  --billing-account=BILLING_ACCOUNT_ID \
  --display-name="prod-folder-monthly" \
  --budget-amount=2000USD \
  --filter-projects=projects/PROJECT_ID \
  --threshold-rule=percent=0.9 \
  --threshold-rule=percent=1.0,basis=forecasted-spend \
  --notifications-rule-pubsub-topic=projects/PROJECT_ID/topics/budget-alerts \
  --notifications-rule-monitoring-notification-channels=projects/PROJECT_ID/notificationChannels/CHANNEL_ID

Flags. --notifications-rule-pubsub-topic names the topic, which must exist and be writable by Cloud Billing. --notifications-rule-monitoring-notification-channels takes channel resource names (list them with gcloud beta monitoring channels list). Check --help for the exact flags available in your release, including --disable-default-iam-recipients.

gcloud billing budgets list and describe

Purpose. Audit the budgets on an account. Free, read-only.

gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID
gcloud billing budgets describe BUDGET_ID --billing-account=BILLING_ACCOUNT_ID
---
amount:
  specifiedAmount:
    currencyCode: USD
    units: '50'
budgetFilter:
  calendarPeriod: MONTH
  creditTypesTreatment: INCLUDE_ALL_CREDITS
  projects:
  - projects/987654321098
displayName: lz-lab-monthly
name: billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/11111111-2222-3333-4444-555555555555
thresholdRules:
- spendBasis: CURRENT_SPEND
  thresholdPercent: 0.5
- spendBasis: CURRENT_SPEND
  thresholdPercent: 0.9
- spendBasis: CURRENT_SPEND
  thresholdPercent: 1.0
- spendBasis: FORECASTED_SPEND
  thresholdPercent: 1.0

Note. The budget filter shows the project number, not the project ID. IDs in the expected output are illustrative.

gcloud projects update --update-labels (write, free metadata)

Purpose. Add allocation labels to a project so that the cost rows carry them from now on.

gcloud projects update PROJECT_ID --update-labels=env=lab,cost-center=cc1234,owner=platform-team
gcloud projects describe PROJECT_ID --format="value(labels)"
{'cost-center': 'cc1234', 'env': 'lab', 'owner': 'platform-team'}

Common error. Label values with uppercase letters or spaces are rejected. Production use. Set labels in the project factory so that no project exists without them.

Query the billing export with bq query (read; BigQuery query cost applies)

Purpose. Cost by project and label for the current month. The export table name contains your billing account ID with dashes replaced by underscores.

bq query --use_legacy_sql=false --project_id=BILLING_PROJECT_ID '
SELECT
  project.id AS project_id,
  (SELECT value FROM UNNEST(labels) WHERE key = "cost-center") AS cost_center,
  ROUND(SUM(cost) + SUM(IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) c), 0)), 2) AS net_cost
FROM `BILLING_PROJECT_ID.billing_export.gcp_billing_export_v1_0X0X0X_0X0X0X_0X0X0X`
WHERE invoice.month = FORMAT_DATE("%Y%m", CURRENT_DATE())
GROUP BY project_id, cost_center
ORDER BY net_cost DESC
LIMIT 20'
+-----------------+-------------+----------+
|   project_id    | cost_center | net_cost |
+-----------------+-------------+----------+
| prj-app-a-prod  | cc1234      |   812.40 |
| prj-app-b-prod  | NULL        |   233.05 |
| prj-sandbox-01  | cc9999      |     4.12 |
+-----------------+-------------+----------+

Notes. NULL in cost_center is the unlabeled cost you must drive to zero. Credits are negative amounts, so the net cost adds them. Query cost depends on bytes scanned; always filter on invoice.month or a partition column, and keep the export dataset in a project with its own budget. Table and column names follow the documented export schema; check the schema page for your export type. Numbers in the output are illustrative.

Production use. Save this query as a scheduled query that writes a monthly summary table, and connect a dashboard (Looker Studio or your BI tool) to the summary table instead of the raw export.

Lab 5: budget with forecast alert and an allocation label (about 12 minutes, free)

Goal. Create a small monthly budget on a sandbox project, confirm that the label and threshold rules are stored as expected, and read the structure of the billing export query without running up cost.

Prerequisites.

  • A sandbox project PROJECT_ID linked to a billing account BILLING_ACCOUNT_ID. Never use a production billing account for a training lab.
  • Permission to create budgets on that billing account (roles/billing.admin, or a custom role with billing.budgets.create) and roles/resourcemanager.projectIamAdmin or roles/owner on the sandbox project to set labels.
  • If you have only a personal billing account, the steps still work; skip step 7 if no export is configured.

Cost. Free. Creating a budget and a label are metadata operations. IDs in the expected output are illustrative.

  1. Set variables and confirm the identity.
    export PROJECT_ID=PROJECT_ID
    export BILLING_ACCOUNT_ID=BILLING_ACCOUNT_ID
    gcloud config set project "$PROJECT_ID"
    gcloud auth list --filter=status:ACTIVE --format="value(account)"
    Verify: the account printed is the one you intend to use.
  2. Confirm the project is linked to the billing account.
    gcloud billing projects describe "$PROJECT_ID" --format="value(billingAccountName,billingEnabled)"
    billingAccounts/0X0X0X-0X0X0X-0X0X0X	True
    Verify: True. If it is False, link it: gcloud billing projects link "$PROJECT_ID" --billing-account="$BILLING_ACCOUNT_ID".
  3. Enable the Budget API.
    gcloud services enable billingbudgets.googleapis.com --project="$PROJECT_ID"
    Verify: gcloud services list --enabled --filter="name:billingbudgets" shows the service.
  4. Label the project for allocation.
    gcloud projects update "$PROJECT_ID" --update-labels=env=lab,cost-center=cc0000,owner=you
    gcloud projects describe "$PROJECT_ID" --format="value(labels)"
    Verify: all three labels appear.
  5. Create the budget.
    gcloud billing budgets create \
      --billing-account="$BILLING_ACCOUNT_ID" \
      --display-name="lz-lab-monthly" \
      --budget-amount=20USD \
      --filter-projects="projects/$PROJECT_ID" \
      --calendar-period=month \
      --threshold-rule=percent=0.5 \
      --threshold-rule=percent=0.9 \
      --threshold-rule=percent=1.0,basis=forecasted-spend
    Verify: the command prints Created budget [...]. Use the currency of your billing account in place of USD if it differs.
  6. Read the budget back and check the rules.
    gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" \
      --format="table(displayName,amount.specifiedAmount.units,amount.specifiedAmount.currencyCode)"
    DISPLAY_NAME    UNITS  CURRENCY_CODE
    lz-lab-monthly  20     USD
    Verify: lz-lab-monthly is listed. Then run describe with the budget ID and count three threshold rules (two actual, one forecast).
  7. (Optional) Read the export. In the console open Billing, Billing export, and note whether BigQuery export is on. If it is, run the cost-by-label query from the commands tab on the billing project, using the real table name from the dataset. Verify: the sandbox project appears, or the result is empty because the project is new.

Expected result. One budget named lz-lab-monthly scoped to the sandbox project, three threshold rules, and a project that carries env, cost-center and owner labels.

Cleanup.

gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(name,displayName)"
gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"

Keep the labels (harmless). Module 7 reuses the budget idea, so you may keep this budget until the end of the hour and then delete it.

Reminder. A budget is an alert, not a cap. The lab creates no billable resources, so it cannot incur spend.

Real cases (typical, not named customers)

  • The forgotten GPU. An experiment left a large accelerator VM running over a long weekend in a project that had no budget. The next month the invoice was the first signal. The fix was layered: a sandbox folder with a low budget on every project, Organization Policy that restricts allowed machine types in the sandbox, a Pub/Sub function that posts to a chat room at 90 percent actual and at 100 percent forecast, and a weekly report of resources older than seven days.
  • Unattributable shared costs. A platform team ran a shared network project and a shared logging project, and finance could not charge them back. The team labeled projects with cost-center and owner, enabled the billing export, and added a monthly allocation rule: shared costs are split by each team's share of directly attributable spend. The unlabeled share was published monthly and fell from a large figure to under a few percent in two quarters.
  • Premature commitment. A group bought a three-year commitment sized on a peak week. After a migration the baseline dropped and part of the commitment went unused. The correction was a rule: commitments are proposed by FinOps from at least three months of export data, cover a conservative share of the steady baseline, and are reviewed quarterly.

Practices

  • Create a budget for every project at creation time (Terraform project factory), with 50, 90 and 100 percent actual and 100 percent forecast rules.
  • Send alerts to a group alias and a shared channel, not to one person's mailbox. A person on leave must not be the single recipient.
  • Enable billing export on day one, to a dedicated project that only the platform and finance groups can read.
  • Make labels mandatory in the project factory and report the unlabeled cost each month.
  • Set quotas on expensive APIs and use Organization Policy to remove risky options (external IPs, unlimited regions) in non-production folders.
  • Review the Recommender idle-resource and rightsizing recommendations each month before buying any commitment.
  • Keep one owner for each budget: a budget with no owner becomes noise.

Security notes

Do not give an automation account billing admin. A function that reacts to a budget message needs only the permission for its action (for example, to change a quota, or to disable one service). Unlinking billing with a broad role can take down a production project at 3 a.m.
  • Billing data reveals business activity. Grant roles/billing.viewer and BigQuery dataset access to groups, not individuals, and review them with the access reviews from Hour 2.
  • A sudden cost spike is often a security signal (leaked service account key, compromised workload). Route the budget Pub/Sub topic to the security team as well as to FinOps, and read the audit logs from Module 1 when a spike has no change record.
  • The billing account is itself a resource with its own IAM policy. Audit who holds roles/billing.admin and log changes to it.

Symptoms and first checks

SymptomLikely causeFirst check
PERMISSION_DENIED creating a budgetThe role is on the project, not on the billing accountgcloud billing accounts get-iam-policy BILLING_ACCOUNT_ID and look for your identity
API [billingbudgets.googleapis.com] not enabledBudget API disabled on the quota projectgcloud services list --enabled --filter="name:billingbudgets"
Budget exists but nobody got an emailOnly default IAM recipients are used and they are not on the account, or the mail was filteredDescribe the budget, check the notification rules, and add a Monitoring channel or Pub/Sub topic
Pub/Sub topic receives nothingTopic in a different project without publisher rights, wrong topic name, or no threshold has been crossed yetCheck the topic name in describe output, then the topic IAM policy
Spend passed 100 percent before any alertBilling data lag, or only the 100 percent rule existsAdd 50, 90 and forecast rules; add quotas for fast runaways
Cost rows show no cost-center labelLabel added after the usage, or resource-level label missingQuery for NULL labels in the export and fix them at the project factory
Export dataset is emptyExport enabled recently (no back-fill) or dataset location mismatchBilling, Billing export in the console; wait up to a day for the first rows
Currency error when creating a budgetAmount currency differs from the billing account currencyCheck the billing account currency in the console, then repeat the amount in that currency

Triage order

  1. Is it a money question or a permission question? Run gcloud billing projects describe PROJECT_ID to confirm the billing link.
  2. List budgets and read the threshold rules and notification settings.
  3. Check the Pub/Sub topic and subscription for the message, and the subscriber logs.
  4. For a cost spike, query the export by service and SKU for the last seven days, then find the project and resource.
  5. Read the Admin Activity audit log for the project for the same period (Module 1) to find who created the resource.
or score ≥ 70% on the quiz

Module 6 · Asset inventory and change history

36–43 · Cloud Asset Inventory search, export, feeds and history for drift and audit reporting
Asset InventorySearchExportFeedsDrift7 min
Learning objectives
  • Search resources and IAM policies across an organization with Cloud Asset Inventory and read the result fields.
  • Export a point-in-time snapshot of assets to Cloud Storage or BigQuery, and explain how snapshots support drift reporting.
  • Create an asset feed that publishes changes to Pub/Sub, and distinguish feeds, history and audit logs.

The short answer

Cloud Asset Inventory (云资产清单) is a metadata service. It keeps an index of resources and IAM policies for an organization, a folder or a project, and lets you search it, export a snapshot, look at a history window, and receive feeds of changes. It does not read your data (no objects, no table rows), and it is not a log. It answers questions such as "which buckets are public?", "which projects have an external IP?", "who has Owner anywhere in this folder?" and "what changed since last Friday?"

What it contains

Content typeWhat you getTypical use
ResourceResource metadata: name, type, location, labels, state, and the resource's own fieldsInventory, label compliance, finding unlabeled cost
IAM policyThe allow policy attached to each resourceWho holds privileged roles, external members, allUsers bindings
Organization PolicyPolicies attached to resourcesShow where constraints are set
Access policyAccess Context Manager policies and perimeters (organization scope)VPC Service Controls review
RelationshipLinks between assets (for example, an instance and its disks)Impact analysis

The four capabilities

  • Search (search-all-resources, search-all-iam-policies): interactive queries with a query language, results paged, eventually consistent within a short time of a change.
  • Export (gcloud asset export): a batch snapshot at a time you choose (including a recent past time), delivered to Cloud Storage or BigQuery. Use it for reports and drift.
  • Feeds (gcloud asset feeds create): near real-time change events to Pub/Sub for the assets and content types you pick.
  • History (gcloud asset get-history): the recorded state of named assets over a recent time window (a limited look-back, check the current limit in the documentation). It is not an unlimited archive; keep your own snapshots for long retention.

There is also policy analysis (gcloud asset analyze-iam-policy), which answers "who can access this resource?" or "what can this identity access?" by expanding groups and roles. Check gcloud asset analyze-iam-policy --help for the flags in your SDK version.

Why it is needed in a landing zone

  1. Visibility. With dozens or hundreds of projects, no one remembers what exists. A scope-level search is the only way to answer inventory questions quickly.
  2. Compliance evidence. Auditors ask for lists: all buckets, all service accounts, all external members. A saved snapshot with a date is evidence.
  3. Drift detection. Terraform state knows what code created. Inventory knows everything. The difference is your unmanaged resources.
  4. Incident response. During an incident you need to find every resource a compromised identity may have created, and every place a role was granted.

How it works internally

Google Cloud services report resource and policy changes to the asset service. The service indexes them by scope. Searches run against this index (so no calls to individual product APIs), which is why a search across thousands of projects returns quickly. The index is eventually consistent: a resource created seconds ago may not show yet, and a deleted one may linger briefly. Export reads the same data into a file. Feeds fan changes out to Pub/Sub as they are indexed, with the old and new state in the asset and priorAsset fields, and a deleted flag for removals.

Search query language

QueryMeaning
name:prodThe name contains prod
labels.env=prodLabel env equals prod
location:europe-west1In that location
state:RUNNINGResource state
NOT labels.cost-center:*Has no cost-center label (check the query syntax page for negation forms in your release)
policy:roles/owner(IAM search) bindings that mention the role

Combine terms with spaces for AND. The documented query syntax is large; keep your own saved queries in the repository next to the code.

When to use which

QuestionUse
"What exists right now?"Search
"Give me everything for the auditor, as a file."Export
"Tell me the moment someone creates a public bucket."Feed (and an Organization Policy to prevent it)
"What did this firewall rule look like last Tuesday?"History (recent) or an older snapshot
"Who did it?"Cloud Audit Logs (Module 1)
"Does the code match reality?"Snapshots plus Terraform plan (Hour 7)

What it is confused with

Often confusedDifference
Asset Inventory vs Security Command CenterInventory lists assets and policies. Security Command Center evaluates them and produces findings (Hour 3). SCC uses asset data, but they are different products.
Asset Inventory vs Audit LogsState of an asset vs the API call that changed it.
Asset Inventory vs Terraform stateState holds only what Terraform manages; inventory sees everything, including console-created resources.
Feeds vs log sinksFeeds publish asset changes; sinks route log entries. A sink on Admin Activity logs gives the actor, a feed gives the new state.
Common misunderstandings. (1) "Inventory is real time." Search is eventually consistent; only feeds are near real time and even they carry a small delay. (2) "History is forever." It has a limited look-back, so export snapshots for long retention. (3) "Search shows everything in the organization." It shows what the caller is allowed to see on that scope.
Google Cloud services Compute · Storage · IAM · ... Cloud Asset Inventory index by scope (org / folder / project) Search search-all-resources search-all-iam-policies Export snapshot to GCS or BigQuery Feeds change events to Pub/Sub History get-history recent window interactive questions monthly report, drift diff alert on public bucket, external IP what did it look like?

Figure 1. One index, four outputs. Choose by the question: interactive, report, event, or recent history.

Terraform state what the code manages Asset export (snapshot) everything that exists Last month's snapshot saved in a bucket Diff: new, deleted, changed in BigQuery or a script Review: adopt into code (terraform import), delete, or accept as exception.

Figure 2. Drift reporting with snapshots. Compare inventory with state and with the previous period, then decide for each difference.

In Figure 1 notice that the index sits between the services and the four outputs, so no search calls the product APIs. In Figure 2, the amber box is the only output that needs a human decision: every item is adopted, removed or explicitly excepted.

The player follows a new VM through the inventory: indexing, a feed message, an alert from a subscriber, a search from the command line, and a scheduled snapshot. The feed and the snapshot are different paths to the same index.

Enable the API once on the project that you use for calls (the quota project): gcloud services enable cloudasset.googleapis.com --project=PROJECT_ID (free). Read commands are free; export and feeds create metadata, and storage or BigQuery costs apply to the files you write. Check gcloud asset --help and each subcommand's --help for the flags in your SDK version.

gcloud asset search-all-resources (read, free)

Purpose. Find resources across a scope without calling each product's API.

gcloud asset search-all-resources \
  --scope=organizations/ORG_ID \
  --query="labels.env=prod" \
  --asset-types=compute.googleapis.com/Instance \
  --format="table(name.basename(),assetType.basename(),location,project)"
NAME          ASSET_TYPE  LOCATION        PROJECT
vm-web-01     Instance    europe-west1-b  projects/987654321098
vm-web-02     Instance    europe-west1-c  projects/987654321098
vm-batch-01   Instance    europe-west1-b  projects/123450987654

Flags. --scope is organizations/ID, folders/ID or projects/ID. --query uses the asset query language. --asset-types filters by type (a comma-separated list). --page-size and --order-by help with large results.

Common errors. PERMISSION_DENIED: ... cloudasset.assets.searchAllResources: grant roles/cloudasset.viewer on the scope. Cloud Asset API has not been used in project ...: enable the API. A newly created resource missing from results: wait a minute, the index is eventually consistent. IDs in the expected output are illustrative.

gcloud asset search-all-iam-policies (read, free)

Purpose. Find who holds a role, or where an external identity has access, across a scope.

gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:roles/owner" \
  --format="table(resource.basename(),policy.bindings.role,policy.bindings.members)"
RESOURCE        ROLE                MEMBERS
prj-legacy-01   ['roles/owner']     ['user:former.employee@example.com']
prj-app-a-dev   ['roles/owner']     ['group:app-a-admins@example.com']

Production use. Run this monthly and report any roles/owner or roles/editor binding to a user (not a group), and any member outside your domain. Table columns depend on the result structure; if a column prints empty, run once with --format=json to see the field names.

gcloud asset export (write: file in Cloud Storage, storage cost applies)

Purpose. Write a snapshot of resources (or IAM policies) to a bucket. This is the evidence file for audits and the input for drift diffs.

gcloud asset export \
  --organization=ORG_ID \
  --content-type=resource \
  --asset-types="compute.googleapis.com/Instance,storage.googleapis.com/Bucket" \
  --output-path=gs://SNAPSHOT_BUCKET/snapshots/2026-11-resource.json \
  --billing-project=PROJECT_ID
Export in progress for root asset [organizations/123456789012].
Use [gcloud asset operations describe organizations/123456789012/operations/ExportAssets/RESOURCE/123456789] to check the status of the operation.

Flags. --organization, --folder or --project choose the root. --content-type is resource, iam-policy, org-policy, access-policy or relationship. --asset-types limits the volume (and the file size). --output-path is a gs:// URI; use --snapshot-time to export an earlier time within the retention window. --billing-project names the project that is billed and has the API enabled. For BigQuery output, use the BigQuery destination flags in gcloud asset export --help.

Common errors. The caller does not have permission on the bucket: the Cloud Asset service agent of the billing project needs write access to the bucket (roles/storage.objectCreator) and the exporting user needs cloudasset.assets.exportResource. Check the operation with the command printed in the output.

Production use. Run it from a scheduled job (Cloud Scheduler plus a function, or CI) under a service account with only the asset exporter permission, write to a retention-locked bucket in the logging project, and keep monthly snapshots for the audit retention period.

gcloud asset feeds create (write, free metadata; Pub/Sub cost is small)

Purpose. Get a message each time an instance is created, changed or deleted.

gcloud pubsub topics create asset-changes --project=PROJECT_ID

gcloud asset feeds create instance-changes \
  --organization=ORG_ID \
  --content-type=resource \
  --asset-types="compute.googleapis.com/Instance" \
  --pubsub-topic=projects/PROJECT_ID/topics/asset-changes
Created feed [organizations/123456789012/feeds/instance-changes].

Flags. --asset-types or --asset-names select what to watch; --content-type selects the payload; --pubsub-topic is the full resource name. Optional --condition-expression filters changes with a CEL expression (check --help). Common errors. No messages: the topic must grant publish rights to the Cloud Asset service agent (service-ORG_NUMBER@gcp-sa-cloudasset.iam.gserviceaccount.com form) or, for project feeds, the project's service agent; the first publish then works. Verify with gcloud asset feeds describe.

gcloud asset feeds list --organization=ORG_ID
gcloud asset feeds delete instance-changes --organization=ORG_ID

gcloud asset get-history (read, free)

Purpose. Show how a specific asset looked over a recent window.

gcloud asset get-history \
  --project=PROJECT_ID \
  --content-type=resource \
  --asset-names="//compute.googleapis.com/projects/PROJECT_ID/global/firewalls/allow-ssh" \
  --start-time=2026-11-20T00:00:00Z \
  --end-time=2026-11-25T00:00:00Z

Flags. --asset-names takes the full resource name (starting with //). --start-time and --end-time are RFC 3339 timestamps. The window is limited by the service retention; older questions need your own snapshots. The result lists each recorded version with its time window; compare the sourceRanges field to see when a rule was widened.

gcloud asset analyze-iam-policy (read, free)

Purpose. Answer "who can reach this resource?" with groups expanded. Check gcloud asset analyze-iam-policy --help for the flags in your SDK version; the documented form uses a scope (--organization), a --full-resource-name, and optional --permissions or --roles filters.

Production use. Keep the five queries your security team asks most (public buckets, external IPs, owners, unlabeled projects, service accounts with keys) as saved scripts in the repository, and run them from CI on a schedule with results sent to the chat channel.

Lab 6: search, snapshot and feed (about 12 minutes, low cost)

Goal. Use the inventory on a sandbox project: search, export a small snapshot to Cloud Storage, create a feed, and trigger and see one change message.

Prerequisites.

  • A sandbox project PROJECT_ID with billing linked and your identity as Owner (or roles/cloudasset.owner and rights to create buckets and topics).
  • Region REGION for the bucket, for example one close to you.
  • No organization needed: all commands use --project.

Cost. Low (usually well under a few USD per day for this lab; in practice a few kilobytes of storage and a handful of Pub/Sub messages). IDs in the expected output are illustrative.

  1. Enable the APIs.
    export PROJECT_ID=PROJECT_ID
    export REGION=REGION
    gcloud services enable cloudasset.googleapis.com pubsub.googleapis.com --project="$PROJECT_ID"
    Verify: gcloud services list --enabled --project="$PROJECT_ID" --filter="name:(cloudasset OR pubsub)" shows both.
  2. Search the project.
    gcloud asset search-all-resources --scope="projects/$PROJECT_ID" --page-size=10 \
      --format="table(assetType.basename(),name.basename())"
    Verify: a short list with at least one row (enabled services appear as resources). Empty output in a brand new project: wait one or two minutes.
  3. Create the snapshot bucket and export.
    export SNAP_BUCKET="${PROJECT_ID}-asset-snapshots"
    gcloud storage buckets create "gs://$SNAP_BUCKET" --project="$PROJECT_ID" \
      --location="$REGION" --uniform-bucket-level-access
    gcloud asset export --project="$PROJECT_ID" --content-type=resource \
      --output-path="gs://$SNAP_BUCKET/snap-1.json"
    Verify: after about a minute, gcloud storage ls "gs://$SNAP_BUCKET/" lists snap-1.json. If the export reports a permission error, grant the Cloud Asset service agent write access to the bucket, as described in the commands tab, and run it again.
  4. Create a topic and a feed.
    gcloud pubsub topics create asset-changes --project="$PROJECT_ID"
    gcloud pubsub subscriptions create asset-changes-sub --topic=asset-changes --project="$PROJECT_ID"
    gcloud asset feeds create lab-feed --project="$PROJECT_ID" --content-type=resource \
      --asset-types="pubsub.googleapis.com/Topic" \
      --pubsub-topic="projects/$PROJECT_ID/topics/asset-changes"
    Verify: gcloud asset feeds describe lab-feed --project="$PROJECT_ID" prints the feed with the topic.
  5. Trigger a change and read the message.
    gcloud pubsub topics create inventory-test --project="$PROJECT_ID"
    sleep 60
    gcloud pubsub subscriptions pull asset-changes-sub --project="$PROJECT_ID" --auto-ack --limit=3 --format=json
    Verify: the JSON contains an asset with a name ending in topics/inventory-test. If the pull is empty, wait another minute and pull again. If it stays empty, check the publisher permission of the Cloud Asset service agent on the topic.
  6. Export again and compare.
    gcloud asset export --project="$PROJECT_ID" --content-type=resource \
      --output-path="gs://$SNAP_BUCKET/snap-2.json"
    sleep 60
    gcloud storage cat "gs://$SNAP_BUCKET/snap-1.json" | wc -l
    gcloud storage cat "gs://$SNAP_BUCKET/snap-2.json" | wc -l
    Verify: snap-2 contains at least one more line than snap-1 (the new topic). A real drift report would diff the asset names, as described in the concepts tab.

Expected result. A search result, two snapshot files in the bucket, one feed message that names the new topic, and a line count that grew by at least one.

Cleanup.

gcloud asset feeds delete lab-feed --project="$PROJECT_ID"
gcloud pubsub subscriptions delete asset-changes-sub --project="$PROJECT_ID"
gcloud pubsub topics delete asset-changes --project="$PROJECT_ID"
gcloud pubsub topics delete inventory-test --project="$PROJECT_ID"
gcloud storage rm --recursive "gs://$SNAP_BUCKET"

Verify the cleanup: gcloud storage buckets list --project="$PROJECT_ID" --filter="name:$SNAP_BUCKET" returns nothing and gcloud asset feeds list --project="$PROJECT_ID" shows no feed.

Real cases (typical, not named customers)

  • Public bucket in minutes, not months. A company relied on a quarterly review to find public buckets. They added an organization feed for storage.googleapis.com/Bucket with iam-policy content, a subscriber that checks for allUsers or allAuthenticatedUsers, and an Organization Policy (iam.allowedPolicyMemberDomains plus public access prevention) so the finding became rare. The feed became the early warning, the policy the prevention.
  • The unmanaged estate. After two years the Terraform state described only 60 percent of the projects. A monthly export to BigQuery, joined with a table of project IDs from Terraform, listed 240 resources that had no code. The team classified them (adopt, delete, exception), and reduced the list each month, with a visible metric.
  • Incident scoping. After a leaked service account key was found, the security team used search-all-iam-policies to find every binding for that account, search-all-resources to find resources created by projects it could reach, and audit logs (Module 1) to find what it did. Inventory gave the map and the audit log gave the timeline.

Practices

  • Enable the Cloud Asset API in a dedicated platform or security project, and use it as the quota and billing project (--billing-project).
  • Grant roles/cloudasset.viewer to security and audit groups at the organization, and keep export permissions narrower.
  • Store snapshots in a bucket with a retention policy and Object Versioning in the logging project, and restrict deletion to a break-glass role.
  • Prefer BigQuery export for monthly reports, because a diff in SQL is easier to review than a file comparison.
  • Always pair a detective control (feed) with a preventive one (Organization Policy, Hour 3).
  • Version your saved queries and feed definitions with Terraform (google_cloud_asset_organization_feed) so that the monitoring itself is reviewed.

Security notes

Inventory is sensitive. A full snapshot is a map of your estate, including IAM bindings and network layout. Treat the snapshot bucket like a security log store: restricted access, retention lock, and no public access.
  • Feed messages contain resource metadata. Restrict the topic and subscription to the security service accounts.
  • Search results respect the caller's permissions, so a person with project-level access cannot see the organization. Do not use a personal account for automation; use a service account with the minimum role.
  • Resource metadata can include labels with business information. Avoid putting secrets or personal data in labels.

Symptoms and first checks

SymptomLikely causeFirst check
Cloud Asset API has not been used in projectAPI disabled on the quota projectgcloud services enable cloudasset.googleapis.com --project=PROJECT_ID and pass --billing-project
PERMISSION_DENIED on searchNo asset role on the scopegcloud organizations get-iam-policy ORG_ID, look for roles/cloudasset.viewer
New resource missing from searchEventual consistencyWait a minute, search again; use a feed for events
Export operation failsService agent cannot write to the bucketgcloud asset operations describe OPERATION_NAME, then the bucket IAM policy
Export file is huge or slowNo --asset-types filterExport by type, or to BigQuery
Feed created but silentTopic permission, asset type typo, or no change occurredgcloud asset feeds describe; trigger a known change
get-history returns nothingOutside the look-back window, or wrong asset name formatUse the full name starting with //; shorten the time window
Search results seem incompleteThe caller sees only part of the scopeRun as an identity with organization-level viewer, or pick a smaller scope

Triage order

  1. Confirm the API and the billing project (--billing-project).
  2. Confirm the permission on the scope (not only on a project below it).
  3. Check the operation (gcloud asset operations describe) for exports.
  4. For feeds, check the topic IAM policy and then publish a manual test message.
  5. If the data looks stale, wait and retry; if it is wrong, compare with the product API for one resource.

Search pages only. Confirm the video date and the commands against the current documentation, because asset flags and content types are extended over time.

Official reading: Cloud Asset Inventory overview · Searching resources · Monitor asset changes with feeds · Export to Cloud Storage.

or score ≥ 70% on the quiz

Module 7 · Lab: organization sink and budget alert

43–53 · Route audit logs to a log bucket, generate and read back an audit event, and set a budget with notifications
Hands-on labLog sinkAudit eventBudget10 min
Learning objectives
  • Create a log bucket and a sink that routes Admin Activity audit logs to it, at project scope or organization scope.
  • Generate an audit event, find it in the source project and in the central bucket, and read who did what.
  • Create a budget with threshold rules and verify it, then clean every resource up in the right order.

What this lab proves

Modules 1 to 6 explained parts of the audit and cost story. This lab connects them in one thread you can repeat in any sandbox: an action happens, it is logged, the log is routed to a central place, you can read who did it, and a budget watches the cost of the exercise. It also shows the one difference between the sandbox and the landing zone: the sink's scope.

Two scopes, one design

Sandbox path (project sink)Landing-zone path (organization sink)
Needs an organization?NoYes
Sink commandgcloud logging sinks create NAME DEST --project=PROJECT_IDgcloud logging sinks create NAME DEST --organization=ORG_ID --include-children
Which entries are seenThose written in that projectThose written anywhere below the organization (with --include-children)
DestinationLog bucket in the same projectLog bucket in a central logging project
Writer identity permissionNot needed for a bucket in the same project (check the current documentation)Needed on the central bucket for the sink's writer identity (for example roles/logging.bucketWriter)
Who may create itProject ownerroles/logging.configWriter on the organization

The commands in this lab are identical in structure for both paths. Use the sandbox path unless your instructor gives you an organization and a logging project.

Why an audit event on purpose

Alerts and sinks are tested by causing the event they are meant to catch. Creating and deleting a Pub/Sub topic is the cheapest safe write: it is metadata only, it costs nothing, it is a configuration change, so it lands in the Admin Activity log, and the audit entry names the principal, the method and the resource.

The three artifacts of the lab

  1. A log bucket (lab-audit), with a 30-day retention. User-defined buckets are the destination for central logging, and they offer retention, location and optional Log Analytics.
  2. A sink (lab-audit-sink) with a filter on the Admin Activity log name, pointing to the bucket.
  3. A budget (lz-lab-h6) on the sandbox project, with a few threshold rules.

How to read an audit entry

An audit log entry is a LogEntry whose protoPayload is an AuditLog object. The fields to read, in order:

FieldTells you
protoPayload.authenticationInfo.principalEmailWho made the call (a user or a service account)
protoPayload.methodNameWhat API method was called
protoPayload.resourceNameWhich resource
protoPayload.serviceNameWhich service
protoPayload.statusSuccess (empty or code 0) or the error
protoPayload.requestMetadata.callerIpWhere the call came from
timestamp and insertIdWhen, and a unique ID for the entry

What you must be able to say after the lab

  • "The Admin Activity entry for the topic creation shows my identity in principalEmail."
  • "The same entry exists in the central bucket, because the sink filter matched it."
  • "The budget exists, has these rules, and only alerts."
  • "Everything I created has been removed, in this order."
Common misunderstandings. (1) "A sink moves logs." It copies them; the source keeps its copy. (2) "A new bucket receives logs automatically." Only a sink routes entries to it. (3) "I can delete the bucket immediately." A deleted log bucket goes through a pending period before it is removed, so plan for it.
gcloud CLI create topic Pub/Sub API CreateTopic Admin Activity audit log principalEmail · methodName · resourceName Sink lab-audit-sink filter: logName activity Log bucket lab-audit · 30 days gcloud logging read --bucket --view Budget lz-lab-h6 watches the whole project: 50 / 90 / 100 % rules. It alerts, it does not stop anything. Cleanup order: sink, topic, bucket, budget. Producer first, destination last.

Figure 1. The lab in one picture. The audit entry travels from the API to the Admin Activity log, the sink copies it to the bucket, and you read it back.

Sandbox: project sink Project Bucket Sees only this project's entries. No organization needed. Same commands, scope flag differs. Landing zone: organization sink prj-a prj-b Org sink Bkt --organization --include-children Writer identity needs bucketWriter.

Figure 2. The only structural difference between the two paths is the sink scope and the destination permission.

Compare the two halves of Figure 2: the lab commands are the same, and the production version adds --organization, --include-children and a role grant for the writer identity.

The player runs the lab as a sequence of real interactions: the topic creation call, the audit entry, the router matching the sink filter, the routed copy, the read-back, and finally the deletion of the sink. Watch the log lines; they are the ones you will see in the commands.

This tab lists every command used in the lab with its purpose and expected result. Run them in the Lab tab, in order. Costs: topic, sink and budget are free metadata; the log bucket ingests only Admin Activity audit entries (free to ingest at the sandbox's volume), so the lab is low cost. Check gcloud logging sinks create --help and gcloud billing budgets create --help for the flags in your SDK version.

gcloud logging buckets create (write, low cost)

Purpose. Create the central bucket, with a retention period.

gcloud logging buckets create lab-audit \
  --project="$PROJECT_ID" \
  --location=global \
  --retention-days=30 \
  --description="Lab: routed audit logs"
Created bucket [lab-audit].
createTime: '2026-11-25T09:12:41.123456789Z'
lifecycleState: ACTIVE
name: projects/prj-lab-0123/locations/global/buckets/lab-audit
retentionDays: 30
updateTime: '2026-11-25T09:12:41.123456789Z'

Flags. --location cannot be changed later, choose it for data residency (use global or a region such as REGION). --retention-days sets how long entries stay (the default for user buckets is 30 days). Common error. Bucket already exists (including a bucket in pending deletion with the same ID): choose a new name.

gcloud logging sinks create (write, free)

Purpose. Route Admin Activity entries to the bucket.

gcloud logging sinks create lab-audit-sink \
  "logging.googleapis.com/projects/$PROJECT_ID/locations/global/buckets/lab-audit" \
  --project="$PROJECT_ID" \
  --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity"'
Created [https://logging.googleapis.com/v2/projects/prj-lab-0123/sinks/lab-audit-sink].
Please remember to grant `serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com` the appropriate permissions on the destination.

Flags. The first positional argument is the sink name and the second the destination. A bucket destination is logging.googleapis.com/projects/PROJECT_ID/locations/LOCATION/buckets/BUCKET_ID. --log-filter uses the Logging query language. In the organization form add --organization=ORG_ID --include-children and omit --project.

Note. The message about granting permissions appears for all sinks. For a destination bucket in the same project as the sink, no extra grant is normally needed; for a central bucket in another project, grant the writer identity roles/logging.bucketWriter on that project. Check the current routing documentation.

gcloud logging sinks describe (read, free)

Purpose. Confirm the filter, destination and writer identity.

gcloud logging sinks describe lab-audit-sink --project="$PROJECT_ID"
createTime: '2026-11-25T09:13:10.001Z'
destination: logging.googleapis.com/projects/prj-lab-0123/locations/global/buckets/lab-audit
filter: logName="projects/prj-lab-0123/logs/cloudaudit.googleapis.com%2Factivity"
name: lab-audit-sink
updateTime: '2026-11-25T09:13:10.001Z'
writerIdentity: serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com

IDs in the expected output are illustrative.

gcloud pubsub topics create (write, free)

Purpose. Generate the audit event. Enable the Pub/Sub API first if needed: gcloud services enable pubsub.googleapis.com.

gcloud pubsub topics create lab-audit-topic --project="$PROJECT_ID"
Created topic [projects/prj-lab-0123/topics/lab-audit-topic].

gcloud logging read (read; reads of the source are free, the bucket query follows log storage rules)

Purpose. Find the audit entry, first in the source project, then in the central bucket.

# In the source (the _Required bucket holds Admin Activity entries)
gcloud logging read \
  'logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \
  --project="$PROJECT_ID" --freshness=1h --limit=3 \
  --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.resourceName)"

# In the central bucket
gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \
  --project="$PROJECT_ID" --bucket=lab-audit --location=global --view=_AllLogs \
  --freshness=1h --limit=3 \
  --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"
TIMESTAMP                       PRINCIPAL_EMAIL         METHOD_NAME                          RESOURCE_NAME
2026-11-25T09:14:02.331Z        you@example.com         google.pubsub.v1.Publisher.CreateTopic  projects/prj-lab-0123/topics/lab-audit-topic

Flags. --freshness limits to recent entries. --bucket, --location and --view read a specific bucket (every user bucket has a _AllLogs view). --limit caps rows. Common errors. Empty result: the sink only routes entries that arrive after it was created, and routing can take a minute; run the topic creation again. Invalid filter: check quote nesting in the shell.

gcloud billing budgets create (write, free metadata)

gcloud billing budgets create \
  --billing-account="$BILLING_ACCOUNT_ID" \
  --display-name="lz-lab-h6" \
  --budget-amount=20USD \
  --filter-projects="projects/$PROJECT_ID" \
  --threshold-rule=percent=0.5 \
  --threshold-rule=percent=0.9 \
  --threshold-rule=percent=1.0,basis=forecasted-spend
Created budget [billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee].

Purpose. Early warning for the sandbox. It alerts and does not cap. Use your billing account currency.

Cleanup commands (writes, free; the bucket enters a pending-deletion period)

gcloud logging sinks delete lab-audit-sink --project="$PROJECT_ID"
gcloud pubsub topics delete lab-audit-topic --project="$PROJECT_ID"
gcloud logging buckets delete lab-audit --project="$PROJECT_ID" --location=global
gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"
Production use. The same sequence, as Terraform: google_logging_project_bucket_config, google_logging_organization_sink (or google_logging_project_sink) and google_billing_budget. The commands in this lab are how you verify what Terraform created.

Lab 7: central audit sink and budget (10 minutes, low cost)

Goal. Route Admin Activity audit logs to a log bucket, cause one audit event, read it back from the source and from the bucket, create a budget, and remove everything.

Prerequisites.

  • A sandbox project PROJECT_ID linked to BILLING_ACCOUNT_ID, with you as Owner. Do not use a production project.
  • gcloud authenticated (gcloud auth list) and the project set as default.
  • APIs: Cloud Logging is on by default; enable pubsub.googleapis.com and billingbudgets.googleapis.com in step 1.
  • Optional organization path: ORG_ID, a central logging project, and roles/logging.configWriter on the organization. The lab marks the differences.
  • No real secrets and no data are involved.

Cost. Low (usually well under a few USD per day for this lab; Admin Activity ingestion is free and the other objects are metadata). Budgets send alerts and do not cap spend. IDs in the expected output are illustrative.

  1. Safety first: variables, billing link and APIs.
    export PROJECT_ID=PROJECT_ID
    export BILLING_ACCOUNT_ID=BILLING_ACCOUNT_ID
    gcloud config set project "$PROJECT_ID"
    gcloud billing projects describe "$PROJECT_ID" --format="value(billingEnabled)"
    gcloud services enable pubsub.googleapis.com billingbudgets.googleapis.com --project="$PROJECT_ID"
    Verify: the describe command prints True.
  2. Create the budget before any other resource. Run the budget command from the commands tab. Verify: gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(displayName)" lists lz-lab-h6. Note the budget ID for cleanup.
  3. Create the log bucket. Run the buckets create command. Verify:
    gcloud logging buckets describe lab-audit --project="$PROJECT_ID" --location=global --format="value(retentionDays,lifecycleState)"
    30	ACTIVE
  4. Create the sink. Run the sinks create command. For the organization path, replace --project with --organization=ORG_ID --include-children, use the central bucket as the destination, and grant the writer identity the bucket writer role on the logging project:
    WRITER=$(gcloud logging sinks describe lab-audit-sink --project="$PROJECT_ID" --format="value(writerIdentity)")
    echo "$WRITER"
    # Only when the destination is in another project:
    # gcloud projects add-iam-policy-binding LOGGING_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter"
    Verify: sinks describe shows your filter, the destination string and a writerIdentity.
  5. Generate the audit event.
    gcloud pubsub topics create lab-audit-topic --project="$PROJECT_ID"
    Verify: gcloud pubsub topics list --project="$PROJECT_ID" --format="value(name)" lists the topic.
  6. Read the event in the source. Run the first logging read command. Verify: one row with your identity as the principal and the method google.pubsub.v1.Publisher.CreateTopic. If the row is missing, wait 30 seconds and run it again; audit entries can take a short time to appear.
  7. Read the event in the central bucket. Run the second logging read command. Verify: the same entry appears. If it does not, create another topic (lab-audit-topic-2), wait a minute, and read again; the sink routes only entries written after it exists. If it still does not appear, run sinks describe and check the filter and destination.
  8. Prove who did it. Print the full entry once as JSON and locate principalEmail, callerIp and userAgent:
    gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \
      --project="$PROJECT_ID" --bucket=lab-audit --location=global --view=_AllLogs \
      --freshness=1h --limit=1 --format=json
    Verify: your own address is in protoPayload.authenticationInfo.principalEmail.
  9. (Optional) Add an exclusion on the sink and see its effect. Create a second sink with a filter that matches nothing you do (for example a different service) and confirm that it routes nothing. This reproduces the most common "missing logs" case from Module 8.

Expected result. The CreateTopic entry exists in the source and in lab-audit, with your identity as the principal. The budget exists and is listed.

Cleanup (in this order).

gcloud logging sinks delete lab-audit-sink --project="$PROJECT_ID"
gcloud pubsub topics delete lab-audit-topic --project="$PROJECT_ID"
gcloud logging buckets delete lab-audit --project="$PROJECT_ID" --location=global
gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"

Verify the cleanup.

gcloud logging sinks list --project="$PROJECT_ID" --format="value(name)"
gcloud logging buckets list --project="$PROJECT_ID" --location=global --format="value(name,lifecycleState)"
gcloud pubsub topics list --project="$PROJECT_ID" --format="value(name)"
gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(displayName)"

The sink and topic lists must not show lab resources. The bucket may be listed as DELETE_REQUESTED for several days, which is normal and free for an empty bucket. The budget list must not show lz-lab-h6.

If you stopped halfway. Run the cleanup anyway; deleting something that does not exist returns a harmless NOT_FOUND. If you use a shared sandbox, also delete any lab-audit-topic-2 from the optional steps.

Real cases (typical, not named customers)

  • Proving a sink, not trusting it. A platform team created an organization sink and assumed it worked because the command succeeded. Months later an auditor asked for evidence, and the bucket was empty because the filter had a typo in the log name. After that, the team added a canary: a scheduled job that creates and deletes a topic in a canary project each day and a Monitoring alert that fires if the CreateTopic entry is not seen in the central bucket within 15 minutes.
  • Writer identity forgotten. A sink to a central bucket in another project was created, but nothing arrived, because the writer identity had no role on the destination. The platform team made the role grant part of the same Terraform module as the sink, so that the sink and its permission can never be separated.
  • Sandbox with a budget from minute one. A training program creates a sandbox project per learner with a small budget, labels and a Pub/Sub notification to the instructor. A forgotten VM from one learner was found by the 50 percent alert before the second day.

Practices

  • Treat every control as unproven until you have seen the evidence: generate the event, then read it from the destination.
  • Keep the lab commands as a smoke test for the landing zone, and run them whenever the logging layer changes.
  • Create sinks and buckets with Terraform, and use the commands only to verify.
  • Set the budget first, create resources second, and delete in reverse order.
  • Use filters that name the log by its full name, so that a sink does not copy more than intended.
  • Put the central bucket in a dedicated logging project that application teams cannot administer.

Security notes

Audit logs are evidence. The identity that can delete a sink or reduce a bucket's retention can hide its own actions. Grant roles/logging.configWriter and roles/logging.admin sparingly, alert on changes to sinks (google.logging.v2.ConfigServiceV2.DeleteSink and UpdateSink), and lock retention on the central bucket.
  • The lab prints your email in the output. Do not paste real audit output into public tickets.
  • Do not use a service account key for the lab. Use your own identity or impersonation.
  • Never route audit logs to a bucket that application teams can read in full; entries include IP addresses and resource names.

Symptoms and first checks

SymptomLikely causeFirst check
Event visible in the source, not in the bucketFilter does not match, or the entry was written before the sink existedgcloud logging sinks describe; create a new event after the sink
Sink created but destination error in the sink metricsWriter identity lacks permission on the destinationDestination IAM policy for the writer identity; grant roles/logging.bucketWriter
Bucket already existsSame ID used before; deleted buckets remain for a pending periodgcloud logging buckets list --location=global; use a new ID
Invalid filterShell quotes broke the filterPrint the filter with echo; use single quotes outside, double inside
PERMISSION_DENIED creating a sinkMissing logging.sinks.creategcloud projects get-iam-policy PROJECT_ID for roles/logging.configWriter
read from the bucket returns nothing but the sink is fineWrong --view or --locationUse --view=_AllLogs and the bucket's location
Budget creation failsNo billing permission or API disabledgcloud services list --enabled --filter="name:billingbudgets", then the billing account IAM policy
Cleanup says NOT_FOUNDAlready deletedHarmless; verify with the list commands

Triage order

  1. Is the entry in the source? If not, the problem is the event or the filter, not the sink.
  2. Describe the sink: filter, destination, writer identity.
  3. Check the destination permission for the writer identity.
  4. Check the sink's own metrics in Cloud Monitoring (logging.googleapis.com/exports/error_count) for delivery errors.
  5. Check exclusions on the source project and the bucket's view.
or score ≥ 70% on the quiz

Module 8 · Troubleshooting logs and cost

53–60 · Missing logs, sink writer permissions, alerts that never arrive, and ingestion cost spikes
TroubleshootingSinksAlertsIngestion cost7 min
Learning objectives
  • Follow a fixed triage order for missing logs: source, filters and exclusions, sink, destination permission, then query.
  • Diagnose a sink that does not deliver and an alert or budget notification that was never received.
  • Find the source of an ingestion cost spike with log volume metrics, and reduce it without losing audit evidence.

The short answer

Troubleshooting logging and cost means walking the path of a log entry or a charge in order and finding where it stopped or grew. Almost every incident in this hour is one of five things: a filter or exclusion removed the entry, a sink did not match or could not write, a permission was missing on the destination, an alert had no working channel, or volume from one producer grew.

The path of a log entry

  1. Source. The workload writes the entry (stdout, agent, API). Was it ever written? Is the Logging agent installed and permitted (roles/logging.logWriter on the workload's service account)?
  2. Cloud Logging API. Quota (write requests per minute) and the entry size limit apply.
  3. Log router. For every entry, each sink evaluates its filter and exclusions. The _Required sink always keeps Admin Activity and System Event audit logs. The _Default sink keeps most other entries unless it is disabled or has exclusions.
  4. Destination. A log bucket (retention, location, views), BigQuery, Cloud Storage or Pub/Sub. The writer identity must be permitted.
  5. Query. You read through a view; the bucket's location, the view and your IAM (log view access) decide what you see.

An entry can be missing at any step. The triage order below checks them from left to right so that each answer narrows the next question.

Why logs go missing

CauseHow it looksFix
Exclusion filterEntries of a type disappear from a bucket after a cost changeReview gcloud logging sinks describe _Default, narrow or remove the exclusion
Sink disabledAll new entries are missing from the destinationgcloud logging sinks update NAME --no-disabled (check --help)
Filter typoSink exists, destination emptyTest the same filter with gcloud logging read on the source
Writer identity without roleSink exists, filter matches, destination empty; sink error metric above zeroGrant roles/logging.bucketWriter (bucket), roles/bigquery.dataEditor (BigQuery), roles/storage.objectCreator (Storage) or roles/pubsub.publisher (Pub/Sub) to the writer identity
Wrong scopeOrganization sink does not contain a project's entriesAdd --include-children, or create the sink at the right level
Retention expiredOld entries goneRaise retention before the data is needed (not retroactively)
Data Access logs not enabledReads of data are not recordedEnable Data Access audit logs for the required services (cost applies)
Wrong view or locationQuery returns empty though the bucket has dataUse --view=_AllLogs and the bucket location

Why sinks fail to deliver

When a sink cannot write, the log router counts errors in logging.googleapis.com/exports/error_count and sends no further notice. The command that created the sink printed success because it only wrote the sink configuration. Always verify a new sink with an end-to-end test (Module 7) and alert on the error metric for production sinks.

Why alerts are not received

  • The alert policy never evaluated true: wrong metric, wrong filter, wrong duration (it must be true for the whole duration window).
  • The policy has no notification channel, or the channel is unverified (email not confirmed) or its webhook is failing.
  • The incident is open and not closed: for metric alerts, a new notification is not sent while the incident remains open, so a recurring condition seems quiet.
  • Notification rate limiting or snooze is active.
  • For budgets: only default recipients are notified, and the thresholds were never crossed, or the Pub/Sub topic is mis-set (Module 5).

Why ingestion cost spikes

Cloud Logging charges for ingested volume into buckets (beyond free allotments, and with exceptions such as the _Required bucket) and for storage beyond the default retention. The usual drivers are:

DriverExample
Debug verbosity left onA release shipped with DEBUG logging in production
Data Access audit logs on a busy serviceBigQuery or Cloud Storage Data Access logs enabled for every project
VPC Flow Logs and firewall rules loggingSampling set to 100 percent on a busy subnet
Load balancer request logsLogging enabled at 1.0 sampling on a high-traffic service
Crash loops and retriesA failing job writes a stack trace every second
Double routingThe same entries stored in _Default and in a central bucket (a second copy is a second ingestion)

Measure first, then reduce: the cheapest fix is almost always at the producer (log level, sampling), then exclusions for low-value entries on _Default, then routing choices (a central bucket for audit, none for debug).

What it is confused with

Often confusedDifference
Exclusion vs retentionAn exclusion stops entries from being stored; retention deletes stored entries after N days.
Exclusion on _Default vs exclusion on a custom sinkThey are independent. Excluding from _Default does not stop a custom sink from routing the same entry.
Alert policy vs budgetAlert policies watch metrics and logs now; budgets watch billed spend with a delay.
Logs vs metrics for alertingMetrics are cheaper and steadier for thresholds; logs fit rare events such as an audit entry.
Common misunderstandings. (1) "If the sink command succeeded, delivery works." It only proves the configuration was saved. (2) "Excluding from _Default saves money everywhere." It does not remove copies stored by other sinks. (3) "Cost spikes are caused by storage." Usually it is ingestion, which is why the fix is at the producer.
1 Source was it written? 2 Filters exclusions? disabled? 3 Sink filter + scope match? 4 Permission writer identity role? 5 Query view, location Evidence for each step 1: gcloud logging read on the source project, with --freshness 2: gcloud logging sinks describe _Default (look for exclusions and disabled) 3: gcloud logging sinks describe NAME (filter, destination, scope) 4: destination IAM policy and the metric exports/error_count 5: gcloud logging read --bucket --location --view=_AllLogs Stop at the first step that gives the wrong answer; that step is the cause.

Figure 1. The five-step triage for a missing log entry. Each step has one command that gives evidence.

Producers app debug logs flow logs LB request logs Data Access logs crash loops Log router sinks + exclusions second reduction point _Default bucket ingestion + storage beyond retention Central audit bucket a second copy is a second ingestion 1: reduce at the source 2: exclude low-value entries 3: route only what you need to keep Never exclude Admin Activity audit logs: they live in _Required and are not billed for ingestion.

Figure 2. Three places to reduce ingestion cost, in order of preference: producer, exclusion, routing.

In Figure 1 read the evidence list below the boxes: each step has exactly one command. In Figure 2, the best saving is on the left because it avoids creating the entry at all.

The player follows a DEBUG entry that is dropped by an exclusion on _Default while ERROR entries are stored and feed an alert policy. It makes the point that "missing" is often a rule that did exactly what it was told.

The troubleshooting set. All read commands are free; the update commands change configuration and are free metadata operations, but exclusions change what is stored, so record the old value first. Check --help for each command in your SDK version.

gcloud logging sinks list and describe (read, free)

Purpose. See every sink at a scope, including _Required and _Default, and read exclusions.

gcloud logging sinks list --project=PROJECT_ID
gcloud logging sinks describe _Default --project=PROJECT_ID
createTime: '2026-03-02T10:00:00.000Z'
destination: logging.googleapis.com/projects/prj-app-a/locations/global/buckets/_Default
exclusions:
- description: Cost review 2026-10
  filter: severity=DEBUG
  name: exclude-debug
filter: NOT LOG_ID("cloudaudit.googleapis.com/activity") AND NOT LOG_ID("externalaudit.googleapis.com/activity") AND NOT LOG_ID("cloudaudit.googleapis.com/system_event") AND NOT LOG_ID("externalaudit.googleapis.com/system_event") AND NOT LOG_ID("cloudaudit.googleapis.com/access_transparency") AND NOT LOG_ID("externalaudit.googleapis.com/access_transparency")
name: _Default

Reading it. The exclusions list shows exclude-debug. Anyone looking for DEBUG entries in _Default will find none. IDs and dates in the expected output are illustrative. For organization sinks add --organization=ORG_ID.

gcloud logging sinks update (write, free metadata)

Purpose. Fix a filter, enable a sink, or change exclusions.

gcloud logging sinks update lab-audit-sink --project=PROJECT_ID \
  --log-filter='logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity"'

# Remove an exclusion from the default sink (flag names: check help)
gcloud logging sinks update _Default --project=PROJECT_ID --remove-exclusions=exclude-debug

Flags. --log-filter replaces the sink filter. Exclusions are managed with --add-exclusion=name=NAME,filter=FILTER and --remove-exclusions=NAME; a sink can be disabled with --disabled and re-enabled with --no-disabled. Check gcloud logging sinks update --help for the flags in your SDK version. Common error. PERMISSION_DENIED: you need roles/logging.configWriter on the scope of the sink.

Production use. Never edit production sinks by hand; change the Terraform, review the plan, and apply. Use the command only to confirm what is deployed.

gcloud logging read to test a filter on the source (read, free for the source)

Purpose. Test whether the entries your sink should match exist. Use the same filter as the sink.

gcloud logging read 'logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName:"SetIamPolicy"' \
  --project=PROJECT_ID --freshness=1d --limit=5 \
  --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"
TIMESTAMP                 PRINCIPAL_EMAIL                RESOURCE_NAME
2026-11-24T16:02:11.120Z  tf-org@prj-seed.iam.gserviceaccount.com  projects/prj-app-a

Reading it. If this finds entries in the source and the destination is empty, the problem is steps 3 or 4 of the triage. If it finds nothing, the problem is the event or the filter text itself. Common error. A filter that uses logName= must have the exact encoded name (%2F for the slash). The : operator is a substring match, = is exact.

Check delivery errors with the sink error metric (read, free)

Purpose. Prove that a sink is failing to write. In Metrics Explorer, chart logging.googleapis.com/exports/error_count, grouped by sink_name. Use the console, or list the metric descriptor:

gcloud monitoring metrics-descriptors describe logging.googleapis.com/exports/error_count --project=PROJECT_ID

Note. If the gcloud monitoring group is not available in your SDK release, use the console or the Monitoring API. Check gcloud monitoring --help. A non-zero value for your sink means the router matched entries but could not write them: look at the destination permission first.

Check the writer identity and destination permission (read, free)

WRITER=$(gcloud logging sinks describe SINK_NAME --project=PROJECT_ID --format="value(writerIdentity)")
echo "$WRITER"
gcloud projects get-iam-policy LOGGING_PROJECT_ID \
  --flatten="bindings[].members" \
  --filter="bindings.members:$WRITER" \
  --format="table(bindings.role)"
ROLE
roles/logging.bucketWriter

Reading it. An empty table means the writer identity holds no role on the destination project. Grant the right role for the destination type (see the concepts tab) with gcloud projects add-iam-policy-binding LOGGING_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter". For a tighter grant, add an IAM condition on the bucket resource name. Check the logging routing documentation for the current recommended form.

Find the noisy producer (read, free)

Purpose. Group ingested bytes by log. The console route is the quickest: Logging, Logs Storage shows the volume per bucket, and Logs Explorer's Log Analytics or Metrics Explorer can group logging.googleapis.com/billing/bytes_ingested by resource_type and log. As a command, list the log names that exist in a project and sample the most recent entries of a suspect:

gcloud logging logs list --project=PROJECT_ID --limit=30
gcloud logging read 'severity=DEBUG' --project=PROJECT_ID --freshness=15m --limit=5 --format="value(logName,resource.type)"
projects/prj-app-a/logs/cloudaudit.googleapis.com%2Factivity
projects/prj-app-a/logs/compute.googleapis.com%2Fvpc_flows
projects/prj-app-a/logs/stdout
projects/prj-app-a/logs/run.googleapis.com%2Frequests

Reading it. Names such as vpc_flows or requests that appear in large volume are candidates for lower sampling. IDs are illustrative.

gcloud logging sinks update _Default --add-exclusion (write, free metadata)

Purpose. Reduce cost by excluding low-value entries from _Default only, after the measurement above.

gcloud logging sinks update _Default --project=PROJECT_ID \
  --add-exclusion='name=exclude-lb-health,description=Health check noise,filter=resource.type="http_load_balancer" AND httpRequest.requestUrl:"/healthz"'

Flags. --add-exclusion takes name, description and filter as comma-separated keys; quote carefully because the filter contains quotes and may contain commas (check --help for the exact syntax). Common mistake. An exclusion that is too wide, such as severity<ERROR, removes every INFO and WARNING entry from _Default, which makes the next incident harder to investigate. Production use. Every exclusion has a name, a description with the ticket number and a review date.

gcloud billing budgets describe (read, free)

Purpose. For "alert not received": inspect the notification rules.

gcloud billing budgets describe BUDGET_ID --billing-account=BILLING_ACCOUNT_ID --format="yaml(displayName,thresholdRules,notificationsRule)"
displayName: prod-folder-monthly
notificationsRule:
  disableDefaultIamRecipients: true
  pubsubTopic: projects/prj-billing/topics/budget-alerts
thresholdRules:
- spendBasis: CURRENT_SPEND
  thresholdPercent: 0.9

Reading it. disableDefaultIamRecipients: true with only a Pub/Sub topic means no email goes to anyone. If nobody reads the topic, the alert is silent. Add a Monitoring channel or re-enable the default recipients. IDs are illustrative.

Production use. Keep this tab as a runbook: five commands (sinks describe, logging read, error metric, IAM check, budgets describe) cover most logging and cost incidents.

Lab 8: break it, find it, fix it (about 15 minutes, low cost)

Goal. Create three deliberate faults in a sandbox, use the triage order to find each one, and fix it. You will practise the exact commands you would use at 3 a.m.

Prerequisites. The sandbox project from Module 7 (PROJECT_ID), roles/logging.configWriter and roles/pubsub.admin (or Owner), and a budget safety net. Do not run this in a shared project. IDs in the expected output are illustrative.

Cost. Low (usually well under a few USD per day for this lab). Budgets alert and do not cap spend.

  1. Prepare.
    export PROJECT_ID=PROJECT_ID
    gcloud config set project "$PROJECT_ID"
    gcloud services enable pubsub.googleapis.com --project="$PROJECT_ID"
    gcloud logging buckets create fault-bucket --location=global --retention-days=7 --project="$PROJECT_ID"
    Verify: gcloud logging buckets list --location=global --project="$PROJECT_ID" --format="value(name)" includes fault-bucket.
  2. Fault 1: filter typo. Create a sink with a deliberately wrong log name, then generate an event.
    gcloud logging sinks create fault-sink-1 \
      "logging.googleapis.com/projects/$PROJECT_ID/locations/global/buckets/fault-bucket" \
      --project="$PROJECT_ID" \
      --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivty"'
    gcloud pubsub topics create fault-topic-1 --project="$PROJECT_ID"
    Wait a minute, then read the bucket:
    gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \
      --project="$PROJECT_ID" --bucket=fault-bucket --location=global --view=_AllLogs --freshness=1h --limit=3
    Observe: the result is empty. Diagnose: the event exists in the source (run gcloud logging read without --bucket), so the problem is the sink; sinks describe fault-sink-1 shows activty. Fix: gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity"', create fault-topic-2 and read again. Verify: the new entry appears.
  3. Fault 2: an exclusion. Add an exclusion to your own sink and see the effect.
    gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" \
      --add-exclusion='name=exclude-all-topics,filter=protoPayload.methodName:"Publisher.CreateTopic"'
    gcloud pubsub topics create fault-topic-3 --project="$PROJECT_ID"
    Observe: after a minute, fault-topic-3 is in the source but not in the bucket. Diagnose: gcloud logging sinks describe fault-sink-1 --project="$PROJECT_ID" lists exclusions. Fix: gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" --remove-exclusions=exclude-all-topics and repeat with fault-topic-4. Verify: the entry for fault-topic-4 arrives.
  4. Fault 3: disabled sink.
    gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" --disabled
    gcloud pubsub topics create fault-topic-5 --project="$PROJECT_ID"
    Observe: no new entry arrives. Diagnose: sinks describe shows disabled: true. Fix: --no-disabled, then test with fault-topic-6. If your SDK rejects these flags, check gcloud logging sinks update --help and use the console toggle.
  5. Practise the cost question. Run the "find the noisy producer" commands from the commands tab on your project. Verify: you can name the three log names with the most entries in the last hour, or confirm the project is quiet.
  6. Write the incident note. For each fault, write two lines: symptom and first check, cause and fix. Compare with the troubleshooting table.

Expected result. After each fix, a new CreateTopic entry appears in fault-bucket. You have seen filter, exclusion, and disabled-sink faults and the one command that exposes each of them (sinks describe).

Cleanup.

gcloud logging sinks delete fault-sink-1 --project="$PROJECT_ID"
for n in 1 2 3 4 5 6; do gcloud pubsub topics delete "fault-topic-$n" --project="$PROJECT_ID" --quiet; done
gcloud logging buckets delete fault-bucket --location=global --project="$PROJECT_ID"

Verify: gcloud logging sinks list --project="$PROJECT_ID" --format="value(name)" shows only _Default and _Required. Topics that were never created return NOT_FOUND, which is harmless.

Real cases (typical, not named customers)

  • The cost-cutting exclusion. A cost review added an exclusion on _Default for everything below ERROR. Two weeks later an outage needed the INFO entries that showed the request path, and they were gone. The team replaced the blanket exclusion with specific ones (health checks, a chatty library), required a ticket and an expiry date on each exclusion, and reduced volume at the producers by changing log levels.
  • The 40 percent surprise. The ingestion bill rose by about 40 percent after a network change. Grouping bytes by log showed VPC Flow Logs at full sampling on one busy subnet. Setting the sampling rate lower and filtering the aggregation interval kept enough data for investigations at a fraction of the volume.
  • The alert that never arrived. A budget notification was set up to a Pub/Sub topic with the default recipients disabled. The subscriber function had failed after a library upgrade, so the 90 percent alert disappeared. The team added a dead-letter subscription, an alert on the subscription's oldest unacknowledged message age, and a monthly test message.

Practices

  • Keep audit logs in _Required and in a central bucket; do not exclude audit entries anywhere.
  • Alert on sink delivery errors, not only on the application.
  • Name every exclusion, give it an owner, a reason and a review date, and keep it in Terraform.
  • Check ingestion volume weekly by log name; a sudden 2x is an incident.
  • Test notification channels every quarter with a test notification.
  • Write the triage order into the on-call runbook and practice it in game days.

Security notes

Silencing is an attack technique. An intruder with logging configuration rights can add an exclusion, disable a sink or shorten retention to hide actions. Alert on UpdateSink, DeleteSink, UpdateBucket, DeleteBucket and changes to exclusions, and restrict roles/logging.admin.
  • Keep a copy of audit logs in a central bucket in a project that workload owners cannot administer, with a locked retention policy.
  • Cost spikes with no matching change record are a security signal; read the Admin Activity log for the same period.
  • Do not paste log excerpts that contain tokens or personal data into tickets; scrub first.

Symptoms and first checks

SymptomLikely causeFirst check
Expected log entries missing from _DefaultExclusion filter, or entries were never writtengcloud logging sinks describe _Default and read the source with a filter
Central bucket empty, source has entriesFilter mismatch, wrong scope, or writer identity without rolesinks describe, then destination IAM policy, then exports/error_count
Org sink does not include one project's entriesMissing --include-children, or the project is in another organizationDescribe the sink at the organization scope
Alert policy never firesMetric or filter wrong, duration longer than the condition lastsChart the same metric in Metrics Explorer for the period
Alert fires in the console, nobody is toldNo notification channel, unverified channel, or open incidentPolicy details: channels; channel verification status
Budget notification not receivedDefault recipients disabled, thresholds not crossed, or topic subscriber failinggcloud billing budgets describe; check the topic and the subscriber
Ingestion cost doubledDebug logs, flow logs sampling, Data Access logs, crash loop, double routingChart billing/bytes_ingested grouped by log; list recent noisy logs
read returns older entries onlyRetention shorter than the question, or index delayBucket retentionDays; wait a minute for recent entries
Cannot delete or change _RequiredIt is managed by Google Cloud and cannot be changedUse a custom bucket for different retention

Triage order

  1. Source. Does the entry or the charge exist where it was produced?
  2. Filters and exclusions. sinks describe _Default and project-level exclusions.
  3. Sink. Describe the sink: filter, scope, disabled, destination string.
  4. Permission. Writer identity role on the destination; sink error metric.
  5. Query. View, location, retention, your own log view access.
  6. For cost: measure by log and resource before changing anything; reduce at the producer first.
  7. For alerts: policy condition, channel, incident state, then the budget notification rules.
or score ≥ 70% on the quiz

Command cheat sheet

Logging, monitoring, audit and cost governance
Hour 6

Hour 6 command cheat sheet: logging, audit, monitoring, inventory and cost

Placeholders are in UPPERCASE: PROJECT_ID, ORG_ID, BILLING_ACCOUNT_ID, REGION. Every command here is documented for the gcloud CLI (current release channel). Flags change between releases, so run gcloud COMMAND --help before you rely on a flag in automation. The "Cost" column in the legend below says whether a write command is free metadata or has a metered effect.

Audit logs and reading logs

CommandPurposeKey flagsGotcha
gcloud logging read 'FILTER'Read log entries from a project, folder, organization or bucket--project, --freshness=1h, --limit, --format, --order=desc, --bucket --location --viewQuote nesting breaks filters. = is exact, : is a substring match. Without --freshness the default window is large and slow.
gcloud logging read 'logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity"'Admin Activity entries (who changed configuration)Add protoPayload.methodName="..." and protoPayload.authenticationInfo.principalEmail="..."The slash in the log name is encoded as %2F. Data Access logs are data_access and are off by default for most services.
gcloud logging logs listList the log names that exist in a project--project, --limitLists names, not volume. Use Metrics Explorer for bytes.
gcloud projects get-iam-policy PROJECT_IDCheck who holds logging or billing roles on a project--flatten="bindings[].members", --filter, --formatShows direct bindings only; inherited bindings come from the folder and organization.

Log buckets and sinks

CommandPurposeKey flagsGotcha
gcloud logging buckets create BUCKET_IDCreate a user-defined log bucket (central destination)--location, --retention-days, --description, --project (also CMEK and analytics flags; check help)Location cannot be changed. A deleted bucket stays for a pending period, and its ID is not reusable during that time.
gcloud logging buckets list / describeCheck retention, location and lifecycle state--location=global, --format="value(retentionDays,lifecycleState)"List needs a location; use global or the region you created the bucket in.
gcloud logging buckets update BUCKET_IDChange retention or description--location, --retention-daysA shorter retention deletes data as soon as it applies. Locking retention is permanent; check the lock flags before using them.
gcloud logging buckets delete BUCKET_IDDelete a user-defined bucket--location, --projectDelete the sinks that point to it first. _Required and _Default cannot be deleted.
gcloud logging sinks create NAME DESTINATIONRoute matching entries to a bucket, BigQuery, Cloud Storage or Pub/Sub--log-filter, --project, --organization, --folder, --include-children, --exclusionThe command succeeds even if the writer identity has no permission. Grant the destination role to the writer identity and test end to end. Bucket destination form: logging.googleapis.com/projects/P/locations/L/buckets/B.
gcloud logging sinks list / describe NAMEInspect filter, destination, exclusions, writer identity--project / --organizationRemember _Required and _Default are sinks too; exclusions live on them.
gcloud logging sinks update NAMEFix a filter, enable or disable, change exclusions--log-filter, --add-exclusion, --remove-exclusions, --disabled, --no-disabledExclusions remove entries silently. Keep a ticket number in the description. Check help for exact syntax in your SDK.
gcloud logging sinks delete NAMERemove a sink--project / --organizationDoes not delete entries already routed. Deleting audit sinks should alert the security team.

Monitoring and alerting

CommandPurposeKey flagsGotcha
gcloud monitoring channels listList notification channels--project, --formatIn older SDK releases the group is under alpha or beta. Check gcloud monitoring --help.
gcloud monitoring policies listList alerting policies and their channels--project, --format="table(displayName,enabled)"An enabled policy with no channel fires silently.
gcloud monitoring policies create --policy-from-file=FILECreate an alerting policy from JSON or YAML--policy-from-file, --projectKeep the file in Terraform or the repository. The file schema follows the AlertPolicy API.
gcloud monitoring metrics-descriptors describe METRICCheck that a metric type exists, for example logging.googleapis.com/exports/error_count--projectMetrics exist only for resources in the metrics scope you query. Check --help if the group is missing.
gcloud logging metrics create NAME --log-filter=FILTER / --config-from-fileCreate a log-based metric (count of matching entries)--description, --log-filterCounts entries only from creation time. Labels create one time series per value; high-cardinality labels raise cost.

Billing, budgets and labels

CommandPurposeKey flagsGotcha
gcloud billing accounts listFind billing account IDs you can use--format="table(name,displayName,open)"Empty output means no billing role for your identity.
gcloud billing projects describe PROJECT_IDCheck the billing link of a project--format="value(billingAccountName,billingEnabled)"billingEnabled: False blocks paid services and API calls that need billing.
gcloud billing projects link PROJECT_ID --billing-account=IDLink a project to a billing account--billing-accountNeeds roles/billing.user on the account and project owner rights. Free metadata change.
gcloud billing budgets createCreate a budget with threshold rules--billing-account, --display-name, --budget-amount=50USD, --filter-projects, --calendar-period=month, --threshold-rule=percent=0.9[,basis=forecasted-spend], --notifications-rule-pubsub-topicBudgets alert, they do not cap spend. Currency must match the account. Needs billingbudgets.googleapis.com.
gcloud billing budgets list / describe / deleteAudit and remove budgets--billing-accountThe filter shows the project number, not the project ID.
gcloud projects update PROJECT_ID --update-labels=k=vAdd allocation labels to a project--update-labels, --remove-labelsLabels apply to future cost rows only. Keys and values are lowercase.
bq query --use_legacy_sql=false 'SQL'Query the billing export in BigQuery--project_id, --use_legacy_sql=false, --dry_runQuery cost depends on bytes scanned. Use --dry_run first and filter by invoice.month. Export has no back-fill.

Cloud Asset Inventory

CommandPurposeKey flagsGotcha
gcloud services enable cloudasset.googleapis.comEnable the API on the quota project--projectAlso pass --billing-project to asset commands when running from another project.
gcloud asset search-all-resourcesSearch resources in a scope--scope=organizations/ORG_ID, --query, --asset-types, --page-size, --formatEventually consistent. Results are limited to what the caller can see.
gcloud asset search-all-iam-policiesFind IAM bindings across a scope--scope, --query="policy:roles/owner"Run as an identity with organization-level viewer rights for complete results.
gcloud asset exportWrite a snapshot to Cloud Storage or BigQuery--organization / --folder / --project, --content-type, --asset-types, --output-path=gs://BUCKET/FILE, --snapshot-timeThe service agent needs write access to the bucket. Filter by asset type to keep the file small.
gcloud asset feeds create FEED_IDPublish asset changes to Pub/Sub--organization / --project, --content-type, --asset-types, --pubsub-topicTopic must allow the Cloud Asset service agent to publish. Test with a known change.
gcloud asset get-historySee an asset's recorded state over a recent window--asset-names="//compute.googleapis.com/...", --content-type, --start-time, --end-timeLimited look-back. Keep snapshots for older questions.

Typical one-liners

# Who created or changed IAM on a project in the last day?
gcloud logging read 'protoPayload.methodName:"SetIamPolicy"' --project=PROJECT_ID --freshness=1d \
  --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"

# Is the central sink healthy? (filter, destination, writer identity)
gcloud logging sinks describe SINK_NAME --organization=ORG_ID

# Which projects have no cost-center label? (resource search; check query syntax in your release)
gcloud asset search-all-resources --scope=organizations/ORG_ID \
  --asset-types=cloudresourcemanager.googleapis.com/Project --format=json

# Budgets on a billing account
gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID --format="table(displayName,amount.specifiedAmount.units)"

Decision shortcuts

QuestionUse
Who did it?gcloud logging read on the Admin Activity log (principalEmail, methodName)
What exists now across the organization?gcloud asset search-all-resources
Evidence file for the auditor?gcloud asset export to a retention-locked bucket
Tell me when a public bucket appears?Asset feed plus Organization Policy to prevent it
Central copy of audit logs?Organization sink with --include-children to a log bucket
Warn me before the bill?Budget with 50, 90, 100 percent actual and forecast rules
Limit damage from a runaway?Quota, Organization Policy, and automation on the budget topic (budgets alone do not cap)
Logs are missing?Source, exclusions, sink filter, writer identity, query view (in that order)
Before production. Flags and output fields change between gcloud releases and some command groups move from alpha or beta to GA. Run gcloud components update in a sandbox, read --help, and prefer Terraform for anything that must be repeated.

Capstone lab and final quiz

Logging, monitoring, audit and cost governance
Hour 6

Capstone lab, Hour 6: a governed audit and cost pipeline

Goal. Build the smallest complete version of the logging, audit and cost layer of a landing zone and prove each part works: a central log bucket with a controlled retention, an audit sink with a verified writer identity, an alert on changes to the sink, an asset snapshot and feed, and a budget with notifications. Then break one part on purpose, find it with the triage order, and clean everything up.

Total time: about 45 minutes. Cost: low (usually well under a few USD per day for this lab). The resources are mostly metadata; log ingestion of Admin Activity entries is free and the data volume is tiny. Budgets send alerts and do not cap spend, so the cleanup at the end is part of the lab. IDs in the expected output are illustrative.

Prerequisites

  • A sandbox project PROJECT_ID with billing linked to BILLING_ACCOUNT_ID, and you as Owner. Never run this in a production project.
  • gcloud CLI (current release channel), authenticated with your own identity. No service account keys, no passwords.
  • Roles for the optional organization path: roles/logging.configWriter and roles/cloudasset.viewer on ORG_ID, and a logging project. Without an organization, every command below works at project scope.
  • A region REGION for the snapshot bucket.

Architecture of the result

  • Audit path: Admin Activity entries from the project go through the sink cap-audit-sink into the log bucket cap-audit (retention 30 days).
  • Detection path: a log-based metric counts changes to sinks, and an alerting policy (console flow) notifies a channel.
  • Inventory path: a snapshot of resources goes to Cloud Storage, and a feed publishes topic changes to Pub/Sub.
  • Cost path: the budget cap-h6-monthly with actual and forecast rules and a Pub/Sub notification topic.

Steps

  1. Variables, billing link, APIs.
    export PROJECT_ID=PROJECT_ID
    export BILLING_ACCOUNT_ID=BILLING_ACCOUNT_ID
    export REGION=REGION
    gcloud config set project "$PROJECT_ID"
    gcloud billing projects describe "$PROJECT_ID" --format="value(billingEnabled)"
    gcloud services enable logging.googleapis.com monitoring.googleapis.com pubsub.googleapis.com \
      cloudasset.googleapis.com billingbudgets.googleapis.com --project="$PROJECT_ID"

    Verification. The describe command prints True. gcloud services list --enabled --filter="name:(cloudasset OR billingbudgets OR pubsub)" shows three services.

  2. Budget first.
    gcloud pubsub topics create cap-budget-alerts --project="$PROJECT_ID"
    gcloud billing budgets create \
      --billing-account="$BILLING_ACCOUNT_ID" \
      --display-name="cap-h6-monthly" \
      --budget-amount=20USD \
      --filter-projects="projects/$PROJECT_ID" \
      --calendar-period=month \
      --threshold-rule=percent=0.5 \
      --threshold-rule=percent=0.9 \
      --threshold-rule=percent=1.0,basis=forecasted-spend \
      --notifications-rule-pubsub-topic="projects/$PROJECT_ID/topics/cap-budget-alerts"

    Verification. gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="table(displayName,amount.specifiedAmount.units)" lists cap-h6-monthly. Describe it and confirm three threshold rules and the topic. Use your billing account currency in place of USD if it differs. If the notification flag is rejected, check gcloud billing budgets create --help and attach the topic in the console.

    DISPLAY_NAME    UNITS
    cap-h6-monthly  20
  3. Allocation labels.
    gcloud projects update "$PROJECT_ID" --update-labels=env=lab,cost-center=cc0000,owner=you

    Verification. gcloud projects describe "$PROJECT_ID" --format="value(labels)" shows the three labels.

  4. Central log bucket.
    gcloud logging buckets create cap-audit --project="$PROJECT_ID" --location=global \
      --retention-days=30 --description="Capstone: routed audit logs"

    Verification. gcloud logging buckets describe cap-audit --project="$PROJECT_ID" --location=global --format="value(retentionDays,lifecycleState)" prints 30 ACTIVE.

  5. Audit sink.
    gcloud logging sinks create cap-audit-sink \
      "logging.googleapis.com/projects/$PROJECT_ID/locations/global/buckets/cap-audit" \
      --project="$PROJECT_ID" \
      --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity"'
    gcloud logging sinks describe cap-audit-sink --project="$PROJECT_ID"

    Verification. The describe output shows your filter, the bucket destination and a writerIdentity. Organization form: create the same sink with --organization=ORG_ID --include-children (no --project), point it to the bucket in the logging project, and grant the writer identity roles/logging.bucketWriter there.

  6. Generate an audit event and read it back.
    gcloud pubsub topics create cap-event-1 --project="$PROJECT_ID"
    sleep 45
    gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic" AND protoPayload.resourceName:"cap-event-1"' \
      --project="$PROJECT_ID" --bucket=cap-audit --location=global --view=_AllLogs \
      --freshness=1h --limit=1 \
      --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName)"
    TIMESTAMP                 PRINCIPAL_EMAIL  METHOD_NAME
    2026-11-25T10:21:07.452Z  you@example.com  google.pubsub.v1.Publisher.CreateTopic

    Verification. One row with your own address as the principal. If it is empty, wait 30 seconds and read again. If it stays empty, run sinks describe (filter and destination), then create cap-event-2; the sink only routes entries written after it exists.

  7. Detect changes to the sink (log-based metric and alert). Create a log-based metric that counts sink changes, then create the alerting policy in the console.
    gcloud logging metrics create cap-sink-changes \
      --project="$PROJECT_ID" \
      --description="Counts UpdateSink and DeleteSink calls" \
      --log-filter='protoPayload.methodName=("google.logging.v2.ConfigServiceV2.UpdateSink" OR "google.logging.v2.ConfigServiceV2.DeleteSink")'

    Console flow. Monitoring, Alerting, Create policy: select the metric logging/user/cap-sink-changes, condition "above 0" over a short window, add a notification channel (your email), name the policy cap-sink-changed. Alternatively, create a log-based alert from Logs Explorer with the same filter.

    Verification. gcloud logging metrics describe cap-sink-changes --project="$PROJECT_ID" prints the filter, and the alerting page lists the policy with one channel. To test, update the sink description or filter once (step 11 does this) and look for the notification and the incident; metrics and alerts can take a few minutes. A policy with no channel is a failed step.

  8. Inventory: search, snapshot, feed.
    export SNAP_BUCKET="${PROJECT_ID}-cap-snapshots"
    gcloud storage buckets create "gs://$SNAP_BUCKET" --project="$PROJECT_ID" \
      --location="$REGION" --uniform-bucket-level-access
    gcloud asset search-all-resources --scope="projects/$PROJECT_ID" --asset-types=pubsub.googleapis.com/Topic \
      --format="table(name.basename(),location)"
    gcloud asset export --project="$PROJECT_ID" --content-type=resource \
      --output-path="gs://$SNAP_BUCKET/cap-snap-1.json"
    gcloud pubsub topics create cap-asset-changes --project="$PROJECT_ID"
    gcloud pubsub subscriptions create cap-asset-changes-sub --topic=cap-asset-changes --project="$PROJECT_ID"
    gcloud asset feeds create cap-topic-feed --project="$PROJECT_ID" --content-type=resource \
      --asset-types="pubsub.googleapis.com/Topic" \
      --pubsub-topic="projects/$PROJECT_ID/topics/cap-asset-changes"

    Verification. The search lists the topics you created. After about a minute gcloud storage ls "gs://$SNAP_BUCKET/" shows cap-snap-1.json. Create a topic (gcloud pubsub topics create cap-event-3), wait one to two minutes, and run gcloud pubsub subscriptions pull cap-asset-changes-sub --auto-ack --limit=3 --format=json: a message names topics/cap-event-3. If the export fails with a permission error, grant the Cloud Asset service agent write access to the bucket and run it again.

  9. Cost visibility check. In the console open Billing, Billing export and note whether BigQuery export is enabled. If yes, run the cost-by-label query from Module 5 against your billing dataset (use --dry_run first).

    Verification. The query returns rows, with a visible cost_center value or NULL for unlabeled cost. If export is not enabled, write down the dataset and project you would use, and note that export is not back-filled.

  10. Break it on purpose, then find it. Edit the sink filter with a typo, create a new event, and use the triage order.
    gcloud logging sinks update cap-audit-sink --project="$PROJECT_ID" \
      --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivty"'
    gcloud pubsub topics create cap-event-4 --project="$PROJECT_ID"
    sleep 60
    gcloud logging read 'protoPayload.resourceName:"cap-event-4"' --project="$PROJECT_ID" \
      --bucket=cap-audit --location=global --view=_AllLogs --freshness=1h --limit=1

    Verification of the fault. The bucket read is empty, while gcloud logging read 'protoPayload.resourceName:"cap-event-4"' --project="$PROJECT_ID" --freshness=1h --limit=1 (the source) returns the entry. Following the triage order: source has it (step 1 passes), no exclusions on _Default apply to this sink (step 2), sinks describe cap-audit-sink shows activty (step 3 fails). Fix with the correct filter, create cap-event-5, and confirm it arrives. The sink change itself should also have produced an UpdateSink entry and, after a few minutes, the alert from step 7.

Expected output summary

PartWhat you should see
Budgetcap-h6-monthly listed, three threshold rules, Pub/Sub topic attached
Labelsenv, cost-center, owner on the project
Log bucketcap-audit, 30 days, ACTIVE
SinkFilter on the Admin Activity log, bucket destination, writer identity present
Audit eventCreateTopic entry in the bucket with your identity as principalEmail
DetectionMetric cap-sink-changes and a policy with a notification channel; an incident after the sink edit
InventoryOne snapshot file and one feed message naming a new topic
FaultEmpty bucket read until the filter typo is fixed; entries appear again afterwards

Cost

Low (usually well under a few USD per day for this lab). Admin Activity audit entries are free to ingest, the log bucket holds only a few entries, Pub/Sub carries a handful of messages, and the snapshot files are tiny. The budget, labels, sink, metric and feed are metadata. A forgotten lab still costs little, but forgotten resources in a real project are how bills grow, so run the cleanup. Budgets send alerts and do not cap spend.

Cleanup (in this order)

gcloud asset feeds delete cap-topic-feed --project="$PROJECT_ID"
gcloud logging sinks delete cap-audit-sink --project="$PROJECT_ID"
gcloud logging metrics delete cap-sink-changes --project="$PROJECT_ID"
gcloud pubsub subscriptions delete cap-asset-changes-sub --project="$PROJECT_ID"
for t in cap-asset-changes cap-budget-alerts cap-event-1 cap-event-2 cap-event-3 cap-event-4 cap-event-5; do
  gcloud pubsub topics delete "$t" --project="$PROJECT_ID" --quiet
done
gcloud storage rm --recursive "gs://$SNAP_BUCKET"
gcloud logging buckets delete cap-audit --project="$PROJECT_ID" --location=global
gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(name,displayName)"
gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"

Delete the alerting policy cap-sink-changed in the console (Monitoring, Alerting) or with gcloud monitoring policies delete POLICY_ID if your SDK has the command, and delete the notification channel if you created it only for this lab. Topics that you did not create return NOT_FOUND, which is harmless.

Verify the cleanup.

gcloud logging sinks list --project="$PROJECT_ID" --format="value(name)"
gcloud logging metrics list --project="$PROJECT_ID" --format="value(name)"
gcloud logging buckets list --project="$PROJECT_ID" --location=global --format="value(name,lifecycleState)"
gcloud pubsub topics list --project="$PROJECT_ID" --format="value(name)"
gcloud asset feeds list --project="$PROJECT_ID"
gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(displayName)"

Only _Default and _Required sinks remain, the metric and feed lists are empty, cap-audit is DELETE_REQUESTED (it disappears after the pending period), no cap- topics remain, and the budget is gone. Keep the project labels if you like; they are free.

What you proved. An action is logged, the log is routed to a central place, you can read who did it, a change to the pipeline itself raises an alert, the estate is inventoried and snapshotted, spend is watched by a budget, and you can find a broken sink with a fixed triage order. In a real landing zone, every step above is Terraform, reviewed and applied by a pipeline (Hour 7).
Check flags before production use. Run gcloud COMMAND --help for every command in your SDK release, and keep the final configuration in Terraform rather than in a shell history.

Knowledge check

Sources and versions

Logging, monitoring, audit and cost governance
Hour 6

Reference documentation for Hour 6

These are the official pages behind the commands and concepts in this hour. They are the source of truth when a flag, a role name, or a default differs from what is written in the course.

Cloud Logging and Cloud Audit Logs

Cloud Monitoring

Cloud Billing, budgets and cost

Cloud Asset Inventory

Landing zone guidance and infrastructure as code

Tools and versions used in this hour

ToolVersion used in the courseHow to check
Google Cloud CLI (gcloud)Current release channel. Cloud Shell always has a current version.gcloud version and gcloud components update (local installs)
bq (BigQuery command-line tool)Installed with the Google Cloud CLIbq version
Terraform (referenced, not required in this hour)Terraform 1.x with the Google provider (pin the major version in required_providers)terraform version
Cloud Logging, Cloud Monitoring, Cloud Billing, Cloud Asset InventoryManaged services; behaviour follows the live documentationRelease notes pages for each product
Check before production use. Flags, defaults, free allotments, retention limits, look-back windows and pricing change over time, and some gcloud command groups move from alpha or beta to GA. Every command in this course was written to be conservative, but you must check gcloud COMMAND --help, the reference pages above and the current pricing pages in a sandbox before you apply anything to a production organization. Keep production changes in Terraform with reviewed plans, not in a shell history.

Examples in this hour use illustrative IDs, project names and dates, and the output blocks are samples of the documented format, not recorded measurements. No prices are quoted: use the official pricing pages and your own billing export.