Cloud Logging in Google Cloud: The Complete Guide to Collecting, Routing, Searching and Governing Logs
A deep, plain-English walkthrough of how Google Cloud captures every log from your applications and infrastructure, how the Log Router decides where each entry goes, and how to search, store, secure and pay for logs in production.
Imagine a huge airport. Hundreds of planes land and take off every day, and every movement is written down by someone: which plane, which gate, what time, was everything normal or did something go wrong. If a bag goes missing, a manager does not interview every worker. They open the records, search for that flight, and see exactly what happened. Now imagine that airport has no records at all. Every problem becomes a guessing game. Cloud Logging is the record-keeping system of Google Cloud. Every virtual machine, container, database, load balancer and API quietly writes down what it is doing, and Cloud Logging collects, stores, searches and protects those notes. This guide explains the whole system, from the smallest log line to company-wide governance, in simple language.
1What Cloud Logging Is and Why It Exists
Cloud Logging is a fully managed service that ingests, stores, searches, analyzes and routes log data from Google Cloud, other clouds and on-premises systems.
The problem it solves
A log is a time-stamped message that a program or system writes to describe something that happened. A user signed in. A payment failed. A disk filled up. A request took four seconds instead of forty milliseconds. In the old days, every server kept its own log files on its own disk. To investigate a problem, an engineer connected to each machine one by one and searched through text files. That approach collapses in the cloud, where servers appear and disappear within minutes, containers live for seconds, and a single user request may touch ten services on ten different machines.
Cloud Logging removes the need to visit machines at all. Logs flow automatically to a central place, they are kept even after the machine that created them is deleted, and they can be searched across the whole organization in seconds. It is serverless, which means you do not install, size or patch any logging servers. You simply send logs and Google handles the storage, indexing and scaling.
Think of Cloud Logging as a central post office and archive for notes. Every building in a city (every service) drops its notes into a mailbox. The post office sorts them, files copies in the right cabinets, throws away junk if told to, and lets anyone with permission look up any note later.
What it is used for
Teams use Cloud Logging for troubleshooting failures, investigating security incidents, proving compliance to auditors, measuring application behavior, triggering alerts, and feeding data into analytics systems. It is deeply connected to the rest of Google Cloud Observability, which also includes Cloud Monitoring for metrics, Cloud Trace for request timing and Error Reporting for grouping crashes.
2Core Concepts You Must Know First
Before going deep, learn the small vocabulary that every later chapter depends on.
Log Entry
One single record describing one event. It has a timestamp, a severity, a source and a payload carrying the actual message or data.
Log
A named collection of log entries that belong together, such as all request logs from one load balancer. Each log has a unique name inside a project.
Monitored Resource
The thing that produced the entry, like a virtual machine, a Kubernetes container or a Cloud Run service. It carries a type and labels such as project, zone and instance.
Severity
A level that says how serious the event was, from DEBUG and INFO up through WARNING, ERROR, CRITICAL, ALERT and EMERGENCY.
Log Bucket
The storage container inside Cloud Logging where entries are kept, with its own retention period, location and optional encryption key.
Sink
A routing rule made of a destination and a filter. It copies matching entries to a bucket, BigQuery, Cloud Storage or Pub/Sub.
Log Router
The engine that receives every incoming entry and checks it against all sinks and exclusion filters to decide where it goes.
Log-based Metric
A number that Cloud Logging calculates from logs, such as the count of errors per minute, which can be charted and used for alerts.
A log entry is a single sticky note. A log is a notebook full of sticky notes about one subject. A bucket is the filing cabinet. The Log Router is the mail sorter, and a sink is a sorting rule that says “copy every red note to the finance department”.
3Anatomy of a Log Entry
Every record in Cloud Logging follows one standard shape called the LogEntry, and understanding its fields is the key to searching well.
The fields that matter most
A LogEntry is a structured object, not just a line of text. The log name tells you which log it belongs to. The resource field describes the source. The timestamp says when the event happened, while a separate receive timestamp says when Cloud Logging got it. These two can differ if a machine was offline and sent its backlog later. The insert identifier is a unique tag that lets Cloud Logging remove duplicates when the same entry is sent twice.
The payload is where the actual content lives, and it comes in three flavors. A text payload is a plain string. A JSON payload is a structured set of named fields, which is by far the most useful because each field becomes searchable. A protocol payload is used mostly by Google services, and audit logs use it to carry rich structured information about who did what.
| Field | What it tells you | Why it matters |
|---|---|---|
| Log name | Which log the entry belongs to | Lets you narrow searches to one source |
| Resource | Type and labels of the producer | Identifies the exact machine, service or container |
| Timestamp | When the event happened | Orders events and powers time-range searches |
| Severity | How serious the event was | Fastest way to find problems |
| Payload | The message or structured data | Holds the real details of the event |
| Labels | Custom key-value tags | Add your own searchable context |
| Trace and span | Links the entry to a request trace | Connects logs across many services |
| HTTP request | Method, URL, status, latency | Standard shape for web traffic analysis |
| Insert ID | Unique identifier | Prevents duplicates |
Whenever you control the application, write logs as structured JSON with clear field names. Cloud Logging will then let you filter by individual fields, build metrics from them and run SQL on them. Plain text forces you to search by guessing words.
A text log is like a handwritten sentence on a napkin. A structured log is like a filled-in form with boxes for name, date and problem. Forms are far easier to sort, count and search than napkins.
4The Families of Logs in Google Cloud
Not all logs come from the same place, and knowing the families helps you decide what to keep, what to protect and what to drop.
Platform Logs
Written by Google Cloud services themselves, such as load balancer request logs, VPC Flow Logs, firewall rule logs, Cloud NAT logs and DNS query logs. You usually switch some of them on, and the service writes them for you.
User-written Logs
Written by your own applications and scripts. On serverless platforms such as Cloud Run, Cloud Functions and App Engine, anything your program prints to standard output or standard error is captured automatically as a log entry.
Agent-collected Logs
Gathered by software installed on virtual machines, mainly the Ops Agent. It reads log files, system logs and third-party application logs from disk and ships them to Cloud Logging.
Security and Audit Logs
Records of who did what to which resource, and who accessed which data. These are the foundation for compliance and incident investigation, and they get their own chapter below.
Multi-cloud and On-premises Logs
Logs from other clouds or private data centers can be sent through the Logging API or agents, so Cloud Logging can serve as a single pane for a hybrid estate.
Many beginners think every log is automatically on. Several high-volume platform logs, such as VPC Flow Logs and load balancer logs, must be enabled and are often sampled. Data Access audit logs are also off by default for most services. Always verify what is actually being collected before an incident forces you to find out.
5Architecture and Main Components
Cloud Logging is made of a small number of clearly separated pieces, each with one job.
The big picture
On the left are the sources: your applications, Google services and agents. They all talk to the Logging API, which is the single front door. Behind that door sits the Log Router, which acts as the traffic controller. The router sends copies of entries to log buckets for storage and to sinks that forward data elsewhere. On the right are the tools people use: the Logs Explorer for searching, Log Analytics for SQL, log-based metrics for numbers and alerts for notifications.
flowchart LR
A["Applications and Services"] --> API["Logging API"]
B["Google Cloud Services"] --> API
C["Ops Agent on VMs"] --> API
API --> R["Log Router"]
R --> F["Exclusion Filters"]
F --> BK["Log Buckets"]
R --> S["Sinks"]
S --> BQ["BigQuery"]
S --> GCS["Cloud Storage"]
S --> PS["Pub/Sub"]
BK --> LE["Logs Explorer"]
BK --> LA["Log Analytics"]
BK --> LM["Log-based Metrics"]
LM --> AL["Alerting"]
Each component in one line
The Logging API accepts entries and checks permissions. The Log Router evaluates routing rules. Buckets hold the data. Sinks copy data to other places. The Logs Explorer is the search screen. Log Analytics lets you ask questions in SQL. Log-based metrics turn logs into numbers. Alerting watches those numbers or the logs themselves and notifies people.
Picture a newspaper building. Reporters (sources) hand stories to the front desk (API). The editor (router) decides which section each story goes in and which stories are dropped. The printing floor and archive (buckets) keep copies, and the distribution team (sinks) sends special editions to other cities.
6Internal Working: How an Entry Is Ingested
Follow a single log line from the moment a program writes it until it becomes searchable.
The event is written
An application prints a message, a Google service records a request, or an agent reads a line from a file on disk.
The entry is packaged and sent
The source wraps the message into the LogEntry shape, attaching the resource description and any labels, and calls the Logging API. Agents and client libraries batch many entries together to save network effort.
The API checks identity and permission
The caller must hold a role that allows writing logs. Entries from callers without permission are rejected before they go any further.
The Log Router takes over
The router compares the entry with every sink and exclusion filter defined at the project, folder and organization levels that apply to it.
Copies are stored and forwarded
Each matching sink receives a copy. Entries sent to a log bucket are indexed and become searchable within seconds. Entries sent to BigQuery, Cloud Storage or Pub/Sub are written there on the sink’s schedule.
Metrics and alerts see the entry
Log-based metrics count or measure matching entries as they arrive, and log-based alert policies can notify people almost immediately.
sequenceDiagram
participant App as Application
participant API as Logging API
participant Router as Log Router
participant Bucket as Log Bucket
participant Sink as Sink Destination
App->>API: Write log entry
API->>API: Check permission
API->>Router: Pass entry
Router->>Router: Apply exclusions and match sinks
Router->>Bucket: Store copy
Router->>Sink: Forward copy
Bucket-->>App: Entry searchable in seconds
Entries are limited in size, around a quarter of a megabyte each. Extremely large messages are truncated or rejected, so avoid dumping entire documents or giant stack dumps into a single entry.
7The Log Router, Sinks and Filters in Depth
The router is where you gain control over cost, compliance and where your data lives.
Two built-in sinks
Every project starts with two sinks already created. The required sink sends audit logs that Google guarantees to keep into a special bucket you cannot change or delete. The default sink sends almost everything else into a general-purpose bucket. You may edit or disable the default sink, but not the required one.
What a sink is made of
A sink has a destination, an inclusion filter and optional exclusion filters. The inclusion filter is a query that describes which entries to copy. If you leave it empty, every entry matches. Exclusion filters then remove entries from that match. Each sink works independently, so the same entry can be copied to several destinations at once without any conflict.
Log Bucket
Keeps data inside Cloud Logging so you can still use the Logs Explorer, Log Analytics and metrics on it.
BigQuery
Writes entries into tables so analysts can run large SQL queries and join logs with business data.
Cloud Storage
Stores batches of entries as files, the cheapest option for long-term archives and compliance retention.
Pub/Sub
Streams entries to a topic so external tools, such as a third-party security platform, can consume them in near real time.
Another Project
Sends logs into a bucket in a different project, ideal for a central security or operations project.
Aggregated sinks
A normal sink only sees logs from its own project. An aggregated sink is created at a folder or organization and collects logs from every project beneath it, including projects created in the future. This is how large companies guarantee that all audit logs land in one protected place, regardless of what individual teams do.
The writer identity
Each sink gets its own service identity, called the writer identity. The destination must grant this identity permission to write. A very common cause of “my sink is not working” is simply that nobody granted that permission on the destination.
flowchart TD
ORG["Organization"] --> FOLD["Folder"]
FOLD --> P1["Project A"]
FOLD --> P2["Project B"]
ORG -. "Aggregated sink" .-> SEC["Central Security Project Bucket"]
FOLD -. "Aggregated sink" .-> ARC["Archive in Cloud Storage"]
P1 -. "Project sink" .-> BQ["BigQuery Dataset"]
P2 -. "Project sink" .-> PS["Pub/Sub Topic"]
An exclusion filter on the default sink does not stop other sinks from receiving the same entry. Likewise, excluded entries are gone from that destination for good, and they also stop feeding log-based metrics that read from that path, so exclude carefully.
8Log Buckets, Retention and Location
Buckets decide how long logs live, where they physically sit and who can see them.
The built-in buckets
The required bucket holds Admin Activity, System Event and similar audit logs, and keeps them for 400 days. You cannot change that period or switch it off. The default bucket holds most other logs and keeps them for 30 days unless you change it. Retention on custom buckets can be set anywhere from one day up to about ten years, and the numbers can change over time, so always confirm current limits in the official documentation.
User-defined buckets
You can create your own buckets for special needs. A bucket for security logs might keep data for several years and allow only the security team to read it. A bucket for noisy debug logs might keep data for only three days to save money. Because routing is done by sinks, you simply create a sink that sends the right logs to the right bucket.
Location matters
Each bucket lives in a chosen region, or in a global setting where Google picks the placement. Data residency rules in some countries or industries require logs to stay inside a specific geography, so choosing the bucket location early is important. Location cannot be changed after the bucket is created, so decide before you start storing data.
Locking a bucket
A bucket can be locked. Once locked, its retention period can never be shortened and the bucket cannot be deleted until every entry has aged out. This is the tool for regulations that demand tamper-proof, write-once retention. It is permanent, so use it only when you are sure.
| Bucket | Typical content | Retention | Can you change it? |
|---|---|---|---|
| Required | Admin Activity and System Event audit logs | 400 days | No |
| Default | Most other logs, Data Access if enabled | 30 days by default | Retention yes, deletion no |
| User-defined | Whatever your sinks send | You choose | Yes, unless locked |
Buckets are like storage rooms in a warehouse. One room is government-sealed and cannot be touched. One is the general room where boxes are thrown away after a month. Others are rooms you rent with your own lock and your own rules, and a locked room means you swore never to open it early.
9Cloud Audit Logs
Audit logs answer the most important security question: who did what, where and when.
Cloud Audit Logs are a special family of logs written by Google Cloud services. They do not describe application behavior. They describe actions taken against Google Cloud resources, and each entry includes the identity of the caller, the method they invoked, the resource affected, the network address they came from and whether the call succeeded.
Admin Activity
Records changes to configuration or metadata, such as creating a virtual machine or changing a permission. Always on, free, and cannot be disabled.
Data Access
Records reading or writing of user data, such as reading a table or listing objects. Off by default for most services because of volume and cost.
System Event
Records actions taken by Google systems rather than people, such as a live migration of a virtual machine. Always on.
Policy Denied
Records when access was refused because of a security policy, such as a perimeter control blocking a request.
Why Data Access logs need a decision
Data Access logs can be enormous because every read creates a record. They are also essential for investigating data leaks. The sensible approach is to enable them for sensitive projects and services, such as those holding customer or financial data, and to leave them off for low-risk, high-volume ones. You can also exempt specific trusted identities, like a known monitoring account, to reduce noise.
Investigating a deleted resource
Someone notices a storage bucket is missing. The Admin Activity log shows the exact identity, time and network address of the person who deleted it, which turns a mystery into a short conversation.
Proving access for an auditor
An auditor asks who read a sensitive dataset last quarter. With Data Access logs enabled and retained, the answer is a search away. Without them, the honest answer is that nobody knows.
Teams often discover that Data Access logs were never turned on only after a suspected breach. Logs cannot be created in the past. Decide in advance which services need them.
10Getting Logs In: Agents, Containers and Serverless
Different compute platforms collect logs in different ways, and knowing which applies saves a lot of confusion.
Virtual machines and the Ops Agent
Compute Engine virtual machines do not send application logs by themselves. You install the Ops Agent, a single agent that collects both logs and metrics. It reads system logs by default and can be configured to read application log files, such as a web server or database log. It handles buffering, so if the network drops briefly, entries are held and sent later. An older, separate logging agent still exists in some environments, but Google recommends the Ops Agent for new work.
Google Kubernetes Engine
On GKE, logs written by containers to standard output and standard error are collected automatically by a node-level component. System logs, workload logs and control plane logs can each be switched on or off at the cluster level. Each entry is tagged with the cluster, namespace, pod and container, which makes it easy to pin down a misbehaving workload.
Cloud Run, Cloud Functions and App Engine
Serverless platforms collect anything printed to standard output or standard error with no setup at all. If the printed line is valid JSON, it is understood as a structured entry, and special field names let you set the severity, attach a trace and add labels. Request logs are written automatically by the platform too.
Other sources
Client libraries exist for popular languages and can write directly to the Logging API. This is useful for programs running outside Google Cloud, including other clouds, laptops and on-premises servers.
| Platform | How logs arrive | Setup effort |
|---|---|---|
| Compute Engine | Ops Agent reads files and system logs | Install and configure agent |
| GKE | Node component captures container output | Cluster setting only |
| Cloud Run and Functions | Platform captures standard output and error | None |
| App Engine | Platform captures requests and output | None |
| Outside Google Cloud | Client library or agent calls the API | Code or agent plus credentials |
A serverless platform is like a hotel that automatically records every guest who walks through the lobby. A virtual machine is like your own house, where you must hire a secretary (the agent) to write down visitors and mail the notes to the central office.
11Searching with the Logs Explorer and Query Language
Collecting logs is useless unless you can find the right five lines among billions.
The Logs Explorer
The Logs Explorer is the main screen for searching. It shows a histogram of log volume over time, a query box, a list of matching entries and a panel for filtering by resource, log name and severity. You can drill into any entry to see every field, and you can jump from an entry to its related trace or to other entries from the same request.
The Logging query language
The query language is built from simple comparisons joined by AND, OR and NOT. You compare fields such as severity, resource type, log name or any field inside a structured payload to a value. You can test for equality, greater-than, containment and pattern matches. You can combine these to say things like “all entries from this service, at error level or above, in the last hour, whose message mentions a timeout”.
Start with resource and time
Narrowing by resource type and a small time window first makes every query faster and cheaper to scan.
Filter by severity
Looking only at warnings and above removes most noise during an incident.
Use structured fields
Searching a named field is exact and fast, whereas searching free text is slower and less reliable.
Follow the trace
Use the trace identifier to see every entry from every service that handled one user request.
Saving and sharing
Useful queries can be saved and shared with teammates so that common investigations, such as “failed logins in the last day”, become one click. Queries can also be turned into log-based metrics or alert policies directly from the screen.
Log scopes and views
Searches normally cover one project, but a scope can combine several projects or buckets into a single search. Log views, covered later, restrict which entries a person can see inside a bucket.
Wide time ranges and unfiltered queries scan far more data. During an incident, begin with the last fifteen minutes, then widen only if needed.
12Log Analytics and BigQuery
Log Analytics adds the power of SQL on top of the same log data you already store.
The Logs Explorer is excellent for finding individual entries. It is less suited to questions like “which ten API methods produced the most errors this week, grouped by customer tier?” For that you need aggregation, and that is what Log Analytics provides. When you upgrade a log bucket to use Log Analytics, you can run SQL-style queries directly on its contents, and charts can be built from the results.
Linked datasets
A bucket with Log Analytics can also be linked to BigQuery. The link creates a read-only dataset that points at the same data, so BigQuery users can query logs and join them with other business data without copying anything and without paying to store a second copy. This is different from a sink to BigQuery, which writes a real copy of the entries into tables.
Linked Dataset Advantages
- No duplicate storage of the same log data
- Data is queryable almost immediately
- Joins logs with sales, user and inventory data
- Access still governed by the bucket’s permissions
Linked Dataset Trade-offs
- Retention is controlled by the bucket, not BigQuery
- The dataset is read-only
- Heavy queries still cost BigQuery compute
Finding the slowest endpoints
An analyst groups request logs by endpoint and calculates the high-percentile latency for each, producing a ranked list that shows exactly where to focus performance work.
Counting suspicious sign-ins
A security team counts failed sign-ins by country and hour, revealing a burst that matches a credential-guessing attack.
The Logs Explorer is like flipping through a ledger to find one receipt. Log Analytics is like putting the whole ledger into a spreadsheet and asking for totals, averages and charts.
13Log-based Metrics and Alerting
Logs tell stories; metrics tell trends. Log-based metrics turn the first into the second.
Two kinds of log-based metrics
A counter metric counts how many entries match a filter, for example the number of payment failures per minute. A distribution metric extracts a numeric value from each matching entry, such as response time, and records how those values are spread, so you can chart averages and high percentiles. Both can be broken down by labels you extract from the logs, such as the service name or error type.
System and user-defined
Google provides some system metrics automatically, such as the number of entries received and bytes ingested. You create user-defined metrics for application-specific signals. Once created, a metric appears in Cloud Monitoring like any other metric, ready for dashboards and alerts.
Alerting from logs
There are two ways to be notified. A metric-based alert watches a log-based metric and fires when it crosses a threshold, such as more than fifty errors in five minutes. A log-based alert fires directly when a matching entry appears, which suits rare, important events like a project owner being added or a firewall rule being deleted. Alerts can notify by email, chat tools, paging systems or webhooks.
flowchart LR
L["Incoming Logs"] --> M["Log-based Metric"]
M --> D["Monitoring Dashboard"]
M --> A1["Metric Alert Policy"]
L --> A2["Log-based Alert Policy"]
A1 --> N["Notification Channels"]
A2 --> N
N --> P["On-call Engineer"]
Creating a metric with too many unique label values causes very high cardinality, which makes metrics expensive and slow. Labels such as user identifiers or request identifiers should never be used as metric labels.
Reading every log is like reading every page of a security guard’s diary. A log-based metric is the guard’s tally sheet that says “seven suspicious visitors tonight”, and an alert is the phone call that wakes you when the tally goes above five.
14Security, Access Control and Privacy
Logs often contain the most sensitive information in your company, so protecting them is as important as collecting them.
Identity and access roles
Access is controlled through Identity and Access Management. A few roles cover most needs. A log writer can send entries but not read them, which is the right role for applications. A viewer can read most logs. A private logs viewer can additionally read the sensitive Data Access audit logs. A configuration writer can create sinks, buckets and metrics. The logging admin can do everything. Follow the principle of least privilege and grant only the smallest role that does the job.
Log views for fine-grained control
A log view is a filtered window onto a bucket. By granting someone access to a view instead of the whole bucket, you can let the payments team see only payment logs while the rest of the bucket stays hidden from them. This is how a shared central bucket can safely serve many teams.
Encryption
All logs are encrypted at rest by default with Google-managed keys. For stricter control, buckets can use customer-managed encryption keys, so your organization controls when the key is disabled or destroyed. Organizations can also set default encryption for all new buckets within a folder or organization.
Protecting sensitive content
Applications sometimes log things they should not, such as passwords, tokens, card numbers or personal data. Once written, such data is stored and searchable. The best protection is prevention: never log secrets, and scrub or mask sensitive fields in the application. Google also offers sensitive data discovery tools that can scan logs for patterns and help you find leaks.
Network perimeter and integrity
VPC Service Controls can place Cloud Logging inside a security perimeter, limiting data exfiltration. Bucket locking and aggregated sinks to a restricted project protect audit evidence from tampering by project owners.
| Role | Can write logs | Can read logs | Can manage config |
|---|---|---|---|
| Logs Writer | Yes | No | No |
| Logs Viewer | No | Yes, most logs | No |
| Private Logs Viewer | No | Yes, including Data Access | No |
| Logs Configuration Writer | No | No | Yes |
| Logging Admin | Yes | Yes | Yes |
Giving every developer broad project-level viewer access often exposes audit logs and personal data they do not need. Use views and narrower roles instead.
15Data Flow and Lifecycle End to End
A log passes through distinct life stages, and every stage offers a decision about cost, speed and retention.
Generation
The event happens and is written. Your choice here is how much detail and structure to include.
Collection
An agent, platform or library delivers it. Your choice is which logs to enable and at what level.
Routing
The router sorts and filters. Your choice is what to keep, what to drop and where copies go.
Hot storage and analysis
Entries sit in buckets for searching, metrics and alerting. Your choice is the retention period.
Archive or export
Entries needed for years are exported to cheaper storage or to analytics systems.
Expiry
When retention ends, entries are deleted automatically. Locked buckets enforce this guarantee in both directions.
graph TD
G["Generate"] --> C["Collect"]
C --> R["Route"]
R --> H["Hot storage in buckets"]
R --> X["Export to BigQuery, Storage, Pub/Sub"]
H --> U["Search, metrics, alerts"]
H --> E["Expire after retention"]
X --> AR["Long-term archive or analytics"]
Log data ages like food in a kitchen. Fresh items sit on the counter for daily use (hot storage), some go into the freezer for long keeping (archive), and anything past its date is thrown out (expiry).
16Design Patterns for Logging Architecture
Experienced teams repeat a handful of proven layouts, and each solves a specific organizational problem.
Central Security Project Pattern
An aggregated sink at the organization level sends all audit logs to a bucket in a dedicated, tightly controlled security project. Individual teams cannot read or alter it, and the security team has one place to search everything.
Tiered Retention Pattern
Recent logs stay in a bucket for fast searching, for example thirty to ninety days. A second sink exports the same logs to low-cost storage for several years. You get speed when you need it and compliance without paying hot-storage prices forever.
Separate Buckets by Sensitivity Pattern
Debug logs, application logs and security logs go to different buckets with different retention, access and encryption. Noise can then be deleted quickly without risking evidence.
Security Information Pipeline Pattern
A sink streams selected logs to Pub/Sub, where a connector forwards them to a company-wide security monitoring platform for correlation with data from other systems.
Per-environment Separation Pattern
Production, staging and development use separate projects, each with its own bucket rules. Production gets longer retention and stricter access, while development logs are short-lived.
flowchart LR
PRJ["Many Projects"] --> AGG["Aggregated Sink"]
AGG --> SB["Security Bucket, long retention, locked"]
AGG --> ARC["Cloud Storage archive"]
PRJ --> LOC["Local Default Bucket, 30 days"]
SB --> SEC["Security Team Only"]
LOC --> DEV["Developers"]
Anti-patterns to avoid
Problem
Leaving everything on defaults and logging every debug message from every service forever.
Why It’s Harmful
Costs balloon, the useful signals drown in noise, and important evidence expires after thirty days.
Correct Approach
Decide per log family what to keep, for how long, and where, using sinks, exclusions and separate buckets.
Problem
Letting each team build its own sinks with no organization-level standard.
Why It’s Harmful
Audit evidence ends up scattered, some projects log nothing, and a project owner can quietly remove their own trail.
Correct Approach
Use aggregated sinks at the organization or folder, owned by a central team, as the baseline that no project can switch off.
Problem
Writing secrets, tokens or personal data into log messages.
Why It’s Harmful
Anyone with log access can read them, and exports copy them to more places, widening the exposure.
Correct Approach
Mask or omit sensitive fields before logging, and review logs regularly for accidental leaks.
17Understanding and Controlling Cost
Logging cost is driven mainly by how much data you ingest, so cost control is really volume control.
What you pay for
At the time of writing, pricing has three main parts. First is ingestion, charged per gibibyte of log data stored into buckets, with a monthly free allowance for each project. Second is storage beyond the free retention period, charged per gibibyte per month. Third is query cost for certain analytics features and any downstream cost in services such as BigQuery, Cloud Storage and Pub/Sub that receive exported data. Some logs, like Admin Activity audit logs, are free. Exact prices and free allowances change, so always check the current official pricing page before budgeting.
Where the volume comes from
The biggest bills usually come from three sources: verbose debug logging left on in production, high-volume network logs such as VPC Flow Logs and load balancer logs captured at full rate, and Data Access audit logs on busy data services.
Exclusion Filters
Drop low-value entries before they are stored, such as health-check requests or debug messages.
Sampling
Keep only a fraction of very repetitive entries, like a percentage of successful requests, while keeping all errors.
Flow Log Tuning
Lower the sampling rate and aggregation detail on network logs, and enable them only on subnets that need them.
Shorter Retention
Reduce the retention of noisy buckets, and export what must live long to cheaper storage.
Right Severity
Run production at info or warning level, and raise detail only temporarily while investigating.
Usage Alerts
Alert on sudden jumps in ingested volume so a runaway loop is caught in hours, not at month end.
Excluding logs in order to save money and then discovering they were needed for an investigation. Exclude only what you are certain has no value, and prefer sampling for anything uncertain.
18Best Practices and Common Mistakes
A short checklist of habits that separate calm production teams from stressed ones.
Best practices
Log in structured form
Use consistent field names across services so one query can span an entire system.
Attach trace identifiers
Include the trace in every entry so a single user request can be followed across services.
Use meaningful severity
Reserve error for things that need action. If everything is an error, nothing stands out.
Centralize audit logs
Use organization-level aggregated sinks into a protected project.
Plan retention early
Match retention to legal and business needs, and document the reasons.
Alert on the important few
Create log-based alerts for rare, high-impact events like permission changes and firewall deletions.
Review regularly
Check volume by source every month, remove noise, and confirm that required logs are still flowing.
Common mistakes
A new sink to another project or to BigQuery silently fails if its writer identity has no permission on the destination. Always check the sink’s error status after creation.
The default bucket keeps logs for only thirty days. Many teams learn this when they search for a six-week-old event and find nothing.
Location is permanent, and mistakes can violate data residency rules. Decide it before you route data in.
If an agent crashes or a sink breaks, logs stop without any noise. Monitor ingestion volume per source so that a sudden drop to zero triggers an alert.
19Real-world and Industry Scenarios
Concrete stories show how the pieces combine when real teams face real pressure.
Online Retail During a Sale
A shopping site expects ten times normal traffic. The team builds a log-based metric counting failed checkouts, sets an alert at a small threshold, and keeps load balancer logs on. When the payment service begins timing out, the alert fires within a minute, and a trace-linked search shows the slow dependency. The fix is deployed before most customers notice.
A Bank Meeting Regulation
A bank must keep audit evidence for seven years and prove it was never altered. It uses an organization-wide aggregated sink into a locked bucket in a restricted security project, plus an export to archive storage. Auditors get read-only access to a log view, and developers never touch the evidence.
A Streaming Service Finding Waste
A media company notices logging costs doubling. Log Analytics shows that one service writes enormous debug entries on every video chunk. The team fixes the log level, adds an exclusion for health checks, and cuts monthly volume dramatically without losing any error information.
A Healthcare Startup Protecting Privacy
A startup discovers that an application logged patient names in error messages. They purge the affected data, change the code to mask fields, add a sensitive data scan, and restrict the application log bucket through log views so that only a small group can read it.
A Platform Team Supporting Many Squads
A central platform team gives each product squad its own project with a default bucket and a shared dashboard template. All audit logs flow centrally through an aggregated sink, and per-squad log views let squads see only their own services, which keeps freedom and governance in balance.
20Advantages, Disadvantages and Trade-offs
No tool is perfect, and a mature team knows both sides before committing.
Advantages
- Fully managed, with no servers to size or maintain
- Automatic collection from most Google Cloud services
- Tight integration with monitoring, tracing and error reporting
- Flexible routing to buckets, BigQuery, storage and Pub/Sub
- Strong audit logging and organization-wide governance
- SQL analysis on the same data through Log Analytics
Disadvantages / Trade-offs
- Costs grow quickly if volume is not managed
- Default retention is short and must be planned for
- Bucket location cannot be changed after creation
- Some important logs are disabled until you enable them
- Most powerful features are specific to Google Cloud, which can complicate portability
Choosing between destinations
| Need | Best fit | Why |
|---|---|---|
| Fast troubleshooting | Log bucket | Searchable in seconds with the Logs Explorer |
| Heavy analysis and joins | BigQuery or linked dataset | Full SQL and business data access |
| Cheap long-term retention | Cloud Storage | Lowest storage cost for archives |
| Real-time external processing | Pub/Sub | Streams to other systems immediately |
| Tamper-proof evidence | Locked bucket | Retention cannot be shortened |
Choosing where to put logs is like choosing where to keep photographs. A desk drawer is quick to reach (bucket), a photo album is good for deep browsing (BigQuery), and a storage unit across town is cheap but slow (Cloud Storage).
21Frequently Asked Questions
Quick answers to the questions beginners ask most often.
For serverless platforms and most Google Cloud services, no. For virtual machines you install the Ops Agent to collect application and system logs. Outside Google Cloud, you use an agent or a client library.
It depends on the bucket. Audit logs in the required bucket are kept for 400 days, while the default bucket keeps entries for 30 days unless you change it. Custom buckets use the retention you set.
You can set very long retention on buckets or export logs to Cloud Storage or BigQuery, where you control retention yourself. Consider the storage cost and any privacy obligations before keeping data indefinitely.
A bucket stores log entries inside Cloud Logging. A sink is a routing rule that decides which entries go to which destination, and a bucket is just one possible destination.
Data Access audit logs are disabled by default for most services. You must enable them for the services you care about, and entries only exist from the moment you turn them on.
The most common causes are a missing permission for the sink’s writer identity on the destination, a filter that matches nothing, or an exclusion filter removing everything. Check the sink’s details for error messages.
Logging deals with individual event records, while Monitoring deals with numeric measurements over time. They work together, and log-based metrics are the bridge that turns log events into measurements.
Yes. Aggregated sinks collect logs into a central bucket, and log scopes let a person search across several projects or buckets, provided they hold permission on each.
The required bucket always keeps Admin Activity and System Event audit logs, and you cannot exclude them from it. You can, however, exclude entries from the default bucket and from your own sinks.
Reduce volume at the source, exclude or sample noisy low-value entries, tune network log sampling, shorten retention on noisy buckets, export long-term data to cheaper storage, and alert on sudden ingestion spikes.
Yes, always at rest and in transit. You can choose customer-managed keys for extra control over buckets.
Prefer structured logs. They make filtering exact, enable metrics from named fields and allow SQL analysis, while plain text relies on fragile word searching.
22Summary and Key Takeaways
Cloud Logging is the memory of your Google Cloud environment. It gathers logs from platforms, applications, agents and security systems through one API, sends each entry through the Log Router, and stores copies in buckets and sinks according to rules you control. On top of that data you search with the Logs Explorer, analyze with SQL in Log Analytics, measure with log-based metrics and react with alerts. Surrounding all of it are governance choices: who can read what, how long data lives, where it physically sits, and how much you are willing to pay. Teams that treat logging as a designed system, with structured entries, central audit collection, deliberate retention and cost awareness, find problems faster, pass audits more easily and spend less. Teams that leave it on defaults tend to learn its limits during their worst incident.
Key Takeaways
- Everything flows through the Log Router — it applies sinks and exclusion filters to decide where each entry is stored or forwarded, and it is your main control point.
- Know your buckets — the required bucket keeps audit logs for 400 days, the default bucket keeps most logs for 30 days, and custom buckets give you control of retention, location, access and encryption.
- Audit logs need deliberate decisions — Admin Activity is always on, but Data Access logs must be enabled in advance because history cannot be recreated.
- Structure beats text — structured JSON logs with trace identifiers unlock precise search, metrics and SQL analysis.
- Centralize governance — use aggregated sinks, log views, locked buckets and least-privilege roles to protect evidence and sensitive data.
- Control volume to control cost — tune log levels, exclusions, sampling and retention, and alert on ingestion spikes before the invoice does.
- Turn logs into action — log-based metrics and alerts convert raw events into early warnings that reach the right person in minutes.