Cloud Logging in Google Cloud: The Flight Recorder for Every Application and Service You Run

Cloud Logging in Google Cloud: The Flight Recorder for Every Application and Service You Run

A complete, plain-English guide to Cloud Logging: how log entries, the Log Router, buckets, sinks, Logs Explorer, Log Analytics, log-based metrics and audit logs work together to help you troubleshoot, secure, audit and understand your systems without drowning in noise or cost.

Imagine an airplane crossing the ocean at night. Pilots cannot see everything that happens inside the engines, so the plane carries a flight recorder that quietly writes down every important event: speeds, alerts, button presses and warnings. When something unusual happens, engineers replay the recorder and understand exactly what occurred. Your cloud applications are just as hidden. Servers run in distant data centers, containers appear and disappear, and users click buttons you will never see. Cloud Logging is the flight recorder for all of it. It collects the messages your systems write, stores them safely, lets you search them in seconds and can alert you when something looks wrong. In this guide we start from the first idea and build up to the choices that keep logging useful, secure and affordable.

1What Is Cloud Logging?

Before diving into features, let us understand what a log is and why a managed logging service matters.

What is a log?

A log is a time-ordered record of something that happened. A web server writes a line every time a page is requested. A database writes a line when a query is slow. A security system writes a line when someone signs in. Each line is called a log entry, and a collection of related entries is called a log. Logs answer the questions “what happened?”, “when?” and “to what?”.

The one-sentence definition

Cloud Logging is Google Cloud’s fully managed service for ingesting, storing, searching, analyzing and alerting on log data from Google Cloud services, your own applications, virtual machines, containers and even other clouds or on-premises systems. It can handle very large volumes of logs without you managing any servers or storage.

Simple Analogy

Think of a hospital. Every patient has a chart where nurses write down temperatures, medicines and observations with the time. When a patient’s condition changes, doctors read the chart to understand why. Logs are the charts of your systems, and Cloud Logging is the records room that keeps every chart organized, searchable and protected.

The problem it solves

Without central logging, every machine keeps its own files. When something breaks, an engineer must connect to servers one by one, hunt through files and hope the machine still exists. Containers vanish within minutes, taking their logs with them. Central logging collects everything into one place before it can disappear, so you can search across your whole system at once.

Automatic
Many Google Cloud services send logs with no setup
Searchable
Query across all projects and services in seconds
Actionable
Turn log patterns into metrics and alerts
i
Good to Know

Cloud Logging is one part of Google Cloud’s observability suite, which also includes Cloud Monitoring for metrics and alerts, Cloud Trace for request tracing and Error Reporting for grouping errors. Logs tell the detailed story; the others give summaries and shapes.

2Why Centralized Logging Matters

Logs are among the most valuable and the most neglected assets in a system.

Purpose 1

Troubleshooting

Find the exact error, the exact time and the exact request that went wrong, instead of guessing.

Purpose 2

Security and Audit

Record who changed what and when, and detect suspicious behavior.

Purpose 3

Compliance

Keep records for the periods that regulations require, with controlled access.

Purpose 4

Performance Insight

Spot slow requests, retries and bottlenecks hiding behind average numbers.

Purpose 5

Business Analytics

Count events such as sign-ups or failed payments, directly from application logs.

Purpose 6

Alerting

Get notified when a particular message or pattern appears.

1

Local Log Files

Each server writes files on its own disk. Hard to search across machines, and lost if the machine disappears.

2

Self-Run Log Servers

Teams build and operate their own collection and search systems, which need constant tuning and capacity planning.

3

Managed Cloud Logging

A scalable service collects logs automatically, stores them and provides search, analytics and alerting.

4

Logs as Data

Logs are analyzed with SQL, turned into metrics and exported to analytics and security tools.

“Logs are the memory of your system. A system without logs forgets everything the moment it breaks.”

3Core Concepts and Vocabulary

A handful of terms appear everywhere in Cloud Logging. Learn them once and the rest feels familiar.

Term 1

Log Entry

A single record with a timestamp, a severity, the resource that produced it and the message or structured data.

Term 2

Log Name

A label that groups related entries, such as the stdout log of a container or the admin activity audit log.

Term 3

Monitored Resource

The thing that produced the entry, such as a virtual machine, a Kubernetes container or a Cloud Run service.

Term 4

Severity

How serious the entry is, from debug and info up through warning, error, critical, alert and emergency.

Term 5

Payload

The content of the entry: plain text, structured JSON or a protocol-defined structure, as in audit logs.

Term 6

Log Router

The pipeline that receives every entry and decides where to store or send it.

Term 7

Log Bucket

A storage container for log entries inside Cloud Logging, with its own location and retention period.

Term 8

Sink

A routing rule that sends matching entries to a destination such as a bucket, BigQuery, Cloud Storage or Pub/Sub.

Term 9

Log-Based Metric

A number derived from log entries, such as the count of errors per minute, which can be charted and alerted on.

Term 10

Logs Explorer

The console tool for searching, filtering and viewing log entries.

Anatomy of a log entry

FieldWhat It HoldsWhy It Matters
TimestampWhen the event happenedLets you order events and look at specific windows of time
SeverityImportance level of the entryLets you filter noise and focus on problems
ResourceType and labels of the source, such as project, region and service nameLets you narrow to one service or location
Log nameWhich log the entry belongs toSeparates kinds of logs, such as request logs and audit logs
PayloadMessage text or structured fieldsHolds the actual details of what happened
LabelsExtra key-value detailsAdd searchable context such as environment or version
Trace and spanIdentifiers linking the entry to a request traceConnects all log lines from one request across services
Insert IDA unique identifier for the entryHelps avoid duplicates and order entries with equal timestamps
Simple Analogy

A log entry is like a line in a ship’s captain’s log: the time, how worried the captain is (severity), which ship and which deck (resource) and what happened (payload). The log router is the mail room that decides which copies of the log go to which offices.

flowchart LR
  A[Applications and Services] --> B[Cloud Logging API]
  B --> C[Log Router]
  C --> D[Log Buckets]
  C --> E[Sinks to Other Destinations]
  D --> F[Logs Explorer and Log Analytics]
  D --> G[Log-Based Metrics and Alerts]
        
FIG 1 — Logs flow from sources, through the Log Router, to storage, analysis and alerting

4Kinds of Logs You Will Meet

Not all logs are the same. Knowing the main categories helps you decide what to keep, what to search and what to pay for.

CategoryWhat It IsTypical Example
Platform logsLogs written by Google Cloud services about their own activityLoad balancer request logs, VPC flow logs, firewall logs
Audit logsRecords of administrative actions and data access in Google CloudWho created a virtual machine or read a storage object
User-written logsLogs your applications write, usually through standard output or the logging librariesApplication messages and business events
Agent-collected logsLogs gathered from virtual machines and other systems by an agentOperating system and web server log files
Container and Kubernetes logsLogs from containers and cluster componentsApplication output and cluster events in Google Kubernetes Engine
Multi-cloud and on-premises logsLogs sent from outside Google CloudServers in your data center writing through an agent or the API

The three families of audit logs

Audit 1

Admin Activity

Records actions that change configuration or metadata, such as creating or deleting resources. Always on, cannot be disabled and not charged.

Audit 2

Data Access

Records reads of configuration or user data and data writes. Off by default for most services because of volume, and billed when enabled.

Audit 3

System Event

Records automated actions by Google systems that change resources, such as moving a virtual machine during maintenance.

Audit 4

Policy Denied

Records when access is denied because of a security policy, helping you spot blocked attempts.

!
Common Mistake

Assuming that all audit logs are on by default. Admin activity logs are, but data access logs usually are not. If you need to know who read a sensitive dataset, you must enable data access logging for that service in advance, because logs cannot be created for the past.

5How Logs Get In: Collection Methods

Logs reach Cloud Logging in several ways, depending on where your workload runs.

Path 1

Automatic from Managed Services

Services such as Cloud Run, Cloud Functions, App Engine and many others send logs without setup. Anything your code writes to standard output or standard error is captured.

Path 2

Google Kubernetes Engine

Cluster logging collects container output and system component logs, with options to choose which categories to send.

Path 3

Ops Agent on Virtual Machines

A single agent installed on Compute Engine or other machines collects system logs, application files and metrics.

Path 4

Client Libraries and the API

Your code can write entries directly using libraries for many languages, which also helps add structure and trace information.

Path 5

Other Clouds and On-Premises

Agents or collectors can forward logs from outside Google Cloud into the same place for unified search.

Path 6

Logging Agents and Open Standards

Common open-source collectors and standard telemetry tools can forward logs to Cloud Logging.

flowchart TD
  A[Cloud Run and Functions: stdout and stderr] --> L[Cloud Logging]
  B[GKE Containers and Cluster Components] --> L
  C[Virtual Machines with Ops Agent] --> L
  D[Google Cloud Platform Logs and Audit Logs] --> L
  E[Applications Using Client Libraries] --> L
  F[On-Premises and Other Clouds] --> L
        
FIG 2 — Many different sources feed one central logging service

Structured versus plain-text logging

A plain-text log line is easy to write but hard to search reliably, because you must match wording. A structured log is a small set of named fields, such as the user identifier, the request path, the status code and the duration. Cloud Logging can store these fields separately, so you can filter and count by them. Structured logging is one of the highest-value habits you can adopt.

Structured Logging Helps With

  • Filtering by exact fields instead of guessing text
  • Counting and grouping events accurately
  • Building log-based metrics with useful labels
  • Carrying severity, trace and request details consistently
  • Analyzing logs with SQL

Plain-Text Logging Struggles With

  • Wording changes breaking searches and alerts
  • Multi-line messages split into separate entries
  • Extracting numbers and identifiers reliably
  • Consistent severity handling
  • Correlating lines from the same request
i
Design Tip

Write one log entry per event, as one structured record, with a clear severity and a request identifier. Avoid splitting a single event across many lines, as multi-line text can turn into many separate, confusing entries.

6The Log Router, Sinks and Exclusions

The Log Router is the traffic controller at the heart of Cloud Logging. Understanding it is the key to controlling cost and compliance.

How routing works

Every log entry that arrives in a project passes through the Log Router. The router compares the entry against a list of sinks. Each sink has a filter that says which entries it wants and a destination that says where to send them. An entry can match several sinks and be sent to several places at once. Exclusion filters on a sink can drop unwanted entries so they are not stored or billed in that destination.

flowchart TD
  IN[Incoming Log Entry] --> R[Log Router]
  R --> S1[Required Sink: Required Bucket]
  R --> S2[Default Sink: Default Bucket with Exclusions]
  R --> S3[Custom Sink: User-Defined Bucket]
  R --> S4[Sink: BigQuery for Analysis]
  R --> S5[Sink: Cloud Storage for Archive]
  R --> S6[Sink: Pub/Sub for External Tools]
        
FIG 3 — One incoming entry can be stored, analyzed, archived and streamed at the same time

Default routing

Each project starts with two built-in sinks. The Required sink sends certain audit logs, such as admin activity and system event logs, to the Required bucket. You cannot change or disable it. The Default sink sends nearly everything else to the Default bucket. You can edit the Default sink, for example to exclude noisy logs, and you can add your own sinks.

Sink destinations

DestinationBest ForNotes
Log bucket in Cloud LoggingSearching, alerting and short to medium retentionMost flexible and best for interactive use
BigQuery datasetLong-term analysis with SQL and joins with other dataGood for reporting and investigations over large time spans
Cloud Storage bucketCheap long-term archive and compliance retentionEntries are written in batches into files
Pub/Sub topicStreaming logs to external tools or custom processingUsed for security tools and third-party platforms
Another project’s log bucketCentral logging project for many projectsSupports centralized security and operations teams

Aggregated sinks

For organizations with many projects, an aggregated sink can be created at a folder or organization level. It collects matching logs from all projects beneath it, which is the basis for central audit log collection and enterprise-wide security monitoring.

Simple Analogy

Imagine a post office sorting room. Every letter arrives on one belt. Workers read the address labels and drop each letter into the right bin: some into the local archive, some into a bin for the finance office, and junk mail into the trash. Sinks are the sorting rules, and exclusions are the rule that throws junk mail away.

ANTI-PATTERN-01 Avoid
Problem

Leaving all noisy, low-value logs flowing into the Default bucket with no review, and then complaining about the logging bill.

Why It’s Harmful

Ingestion is billed by volume. High-volume logs such as health checks and debug messages can dominate costs while giving little value.

Correct Approach

Review which logs produce the most volume, exclude what you never read, and route what you need only for compliance to cheaper destinations.

!
Common Mistake

Excluding logs that you may need during an incident or audit. Excluded entries are not stored in that destination, and they cannot be recovered. Exclude only what you are confident you will not need, and consider keeping a sample.

7Log Buckets, Retention and Log Views

Where logs are stored, for how long, and who can see them, are decisions with both cost and security consequences.

Log buckets

A log bucket is a storage container inside Cloud Logging that holds log entries. Each project has the Required bucket, which holds certain audit logs for a fixed long period at no charge, and the Default bucket, which holds most other logs for a shorter default period. You can create your own buckets, each with its own location and retention period, to separate logs by purpose, team, sensitivity or compliance need.

BucketWhat It HoldsRetentionCan You Change It?
RequiredAdmin activity, system event and access transparency logsA fixed long periodNo, retention and routing are fixed
DefaultAll other logs unless routed elsewhereA default shorter period, configurableYes, you can change retention and the sink filters
User-definedLogs you route to itYou choose, from days to many yearsYes, fully configurable

Retention and location

Retention is how long entries are kept before being deleted automatically. Storing logs for longer increases cost, so set retention to match real needs. Each bucket also has a location, either a specific region or a global setting. Choose a location that meets data residency requirements, as it cannot be changed after creation. Buckets can also be protected with customer-managed encryption keys and locked so that retention cannot be shortened.

Log views: controlling who sees what

A log view is a saved filter on a bucket that limits which entries a person can see. Instead of giving a team access to a whole bucket full of everyone’s logs, you give them access to a view that shows only their service’s entries. This is a clean way to share a central logging bucket across many teams while keeping each team’s data private.

flowchart TD
  B[Central Log Bucket: All Production Logs] --> V1[View: Payments Team Entries]
  B --> V2[View: Web Team Entries]
  B --> V3[View: Security Team All Entries]
  V1 --> U1[Payments Engineers]
  V2 --> U2[Web Engineers]
  V3 --> U3[Security Analysts]
        
FIG 4 — Views give each team access only to the entries they should see
Simple Analogy

A bucket is a big filing room. A view is a pair of glasses that lets a person see only the folders belonging to their department, even though the whole room is shared.

i
Design Tip

Create separate buckets when logs have different retention, location or sensitivity requirements, and use views when you only need different audiences for the same data. Do not create a bucket for every small service; too many buckets make management harder.

8Logs Explorer and the Logging Query Language

Collecting logs is useless if you cannot find the right line quickly. Logs Explorer is your search window.

What Logs Explorer offers

Logs Explorer is the main console tool for viewing logs. It shows a histogram of entries over time, a list of matching entries and a field panel to filter by resource, severity and other fields. You can build queries by clicking fields, by typing text, or by writing queries in the Logging query language. It also supports live tailing, which streams new entries as they arrive, and sharing links to a specific query for teammates.

The Logging query language

The query language is a simple way to describe which entries you want. You combine conditions about fields, such as the resource type, the severity, a field inside a structured payload or a time range, with the words AND, OR and NOT. It also supports comparisons and text matches. Learning to write precise queries is the difference between finding the answer in seconds and scrolling for an hour.

Filter 1

By Resource

Limit to one service, cluster, virtual machine or project to cut noise.

Filter 2

By Severity

Show only warnings and above, or only errors, during an incident.

Filter 3

By Time Window

Narrow to the minutes around the problem, which makes patterns stand out.

Filter 4

By Payload Field

Match structured fields such as a status code, user identifier or request path.

Filter 5

By Text

Search for specific words or phrases when logs are plain text.

Filter 6

By Trace

Show every entry from every service that handled one request.

1

Set the Time Window

Start with the period around the symptom, not the whole retention period.

2

Pick the Resource

Select the service or cluster involved.

3

Raise the Severity Bar

Filter to errors and warnings first.

4

Find a Representative Entry

Open one failing entry and note its fields, trace and request identifier.

5

Pivot to the Full Story

Filter by that trace or identifier to see every related entry across services.

i
Practical Insight

Save your most useful queries and share them with the team. A shared library of queries for common problems, such as “all errors for the checkout service in production”, turns individual experience into team knowledge.

!
Common Mistake

Searching a huge time range with a vague text query, then concluding the logs are “too slow”. Narrow the time window and use resource and field filters first. Specific queries are fast and cheap; broad ones are slow.

9Log Analytics: SQL Over Your Logs

Sometimes searching is not enough. You want to count, group, join and measure. Log Analytics brings SQL to logs.

What Log Analytics is

Log Analytics lets you run SQL queries over your logs directly inside Cloud Logging. You upgrade a log bucket to use Log Analytics, and its entries become queryable like a table. You can group by fields, calculate averages and percentiles, find the top error messages, and chart results in the console. You can also create a linked dataset so BigQuery can query the same logs without copying them, which allows joining logs with business data.

AspectLogs ExplorerLog Analytics
Main purposeFind and read specific entriesAggregate, group and analyze many entries
Query styleLogging query language filtersSQL
Typical questionWhat happened to this request?Which endpoints had the most errors last week?
OutputList of entries and histogramTables and charts of results
Best forTroubleshooting incidentsTrends, reports, security hunting and capacity analysis
Simple Analogy

Logs Explorer is like searching through a pile of receipts for one specific purchase. Log Analytics is like pouring all the receipts into a spreadsheet to ask “how much did we spend on each category this quarter?”

Typical analytics questions

Question 1

Top Errors

Which error messages are the most frequent, and which services produce them?

Question 2

Latency Patterns

What are the slowest request percentiles per endpoint and per version?

Question 3

Security Hunting

Which identities performed unusual administrative actions, and from where?

Question 4

Traffic Analysis

Which sources send the most traffic to a load balancer, and which are blocked?

Question 5

Cost Understanding

Which services produce the most log volume and so the most logging cost?

i
Good to Know

Log Analytics works best with structured data. The cleaner and more consistent your log fields, the more powerful and reliable your SQL questions become. Check current documentation for supported features and any related charges.

10Log-Based Metrics and Alerts

Logs describe individual events. Metrics describe trends. Log-based metrics turn one into the other.

What a log-based metric is

A log-based metric is a number that Cloud Logging calculates from log entries matching a filter you choose. A counter metric counts how many matching entries occurred, such as the number of failed payments per minute. A distribution metric records values extracted from entries, such as request durations, so you can chart percentiles. Labels extracted from the entries, such as the service name or error type, let you slice the metric by category.

Type 1

Counter Metrics

Count matching entries over time. Good for error counts, sign-ups and specific events.

Type 2

Distribution Metrics

Capture the spread of numeric values such as latency, enabling percentile charts.

Type 3

System-Defined Metrics

Predefined by Google, such as counts of log entries and bytes ingested, useful for tracking logging volume.

Type 4

User-Defined Metrics

Created by you from your own filters and extracted fields.

Alerting from logs

Cloud Monitoring can alert on log-based metrics, notifying you when an error rate crosses a threshold. For rare but important messages, log-based alerts can notify you directly when a matching entry appears, without building a metric first, for example when a critical security event is logged. Notifications can go to email, chat tools, incident management systems and webhooks.

flowchart LR
  L[Log Entries] --> F[Filter for Specific Pattern]
  F --> M[Log-Based Metric]
  M --> C[Chart and Dashboard]
  M --> A[Alert Policy]
  A --> N[Notification to On-Call Team]
  F --> LA[Log-Based Alert for Rare Events]
  LA --> N
        
FIG 5 — Logs become metrics and alerts that tell people when to act
Simple Analogy

A smoke detector does not store every puff of air; it counts particles and sounds an alarm above a threshold. A log-based metric counts patterns in your logs, and an alert policy is the alarm that rings when the count is too high.

ANTI-PATTERN-02 Avoid
Problem

Creating metrics with high-cardinality labels, such as a unique user identifier or request identifier as a label.

Why It’s Harmful

Each unique label value creates a separate time series, which can explode in number, slow dashboards and increase monitoring costs.

Correct Approach

Use labels with a small, bounded set of values such as service, status class or environment, and use logs themselves to drill down to individual requests.

11Correlating Logs with Traces and Errors

A single user request may pass through many services. Correlation ties all their log lines together.

Trace and span identifiers

When your request flows through services, each service can record a trace identifier in its log entries. Cloud Logging uses the trace and span fields to link entries to traces in Cloud Trace. With correct fields, you can click from a slow request in a trace to all log lines produced during that request, across every service. Many Google Cloud services add these fields automatically, and your own code can add them using client libraries or standard formats.

Error Reporting

Error Reporting watches logs for exceptions and stack traces, groups similar errors together, counts how often they occur and notifies you of new ones. Instead of reading thousands of repeated error lines, you see a short list of distinct problems and their frequency.

Tool 1

Cloud Trace

Shows the path and timing of a request through services, pointing to the slow step.

Tool 2

Cloud Logging

Shows detailed messages from each step with the trace identifier as the link.

Tool 3

Error Reporting

Groups exceptions into distinct issues with counts and first-seen times.

Tool 4

Cloud Monitoring

Shows trends and fires alerts that start an investigation.

1

An Alert Fires

Error rate rises above the threshold in Cloud Monitoring.

2

Check Error Reporting

See which exception is new or growing, and how many users are affected.

3

Open a Failing Trace

Find the slow or failing step across services.

4

Read the Related Logs

Use the trace identifier to read every log line for that request, revealing the cause.

!
Common Mistake

Logging without any request identifier. When thousands of requests interleave, you cannot tell which lines belong together. Always include a request or trace identifier in every log line.

12Audit Logging for Security and Compliance

Audit logs answer the most important security question: who did what, where and when?

What an audit log entry tells you

Audit log entries record the identity that made the call, the method that was called, the resource affected, the time, the source address and whether the request succeeded or was denied. This lets you reconstruct events during an investigation, prove compliance and detect unusual behavior such as a new administrator being added at midnight.

1

Rely on Default Admin Logs

Administrative changes are recorded automatically and kept in the Required bucket.

2

Enable Data Access Logs Where Needed

Turn on data access logging for sensitive services, accepting the added volume and cost.

3

Aggregate Centrally

Use an organization-level sink to send audit logs from all projects to a central, protected location.

4

Retain and Lock

Set retention to match regulations, and lock buckets so retention cannot be shortened.

5

Analyze and Alert

Query audit logs and alert on high-risk actions such as permission changes or key deletions.

Alert 1

Permission Changes

Someone granted or changed high-privilege roles.

Alert 2

Service Account Key Creation

New long-lived keys created, a common risk indicator.

Alert 3

Firewall and Network Changes

Rules opened to the whole internet or critical networks altered.

Alert 4

Logging Configuration Changes

Someone changed sinks, exclusions or retention, which could hide activity.

Alert 5

Denied Access Spikes

Many policy-denied events may indicate probing or misconfiguration.

i
Design Tip

Protect the logs that watch the watchers. Store central audit logs in a separate project with tightly limited access, so that someone who compromises a workload project cannot erase evidence of what they did.

13Security, Privacy and Access Control

Logs often contain sensitive details. Protecting them is as important as protecting the systems that produce them.

Controlling access with IAM

Role 1

Logs Viewer

Can view most logs, excluding certain private ones such as data access audit logs.

Role 2

Private Logs Viewer

Can also view sensitive categories such as data access audit logs. Grant carefully.

Role 3

Logs Writer

Can write log entries, suitable for workloads and agents.

Role 4

Logs Configuration Writer

Can manage sinks, buckets and exclusions. Powerful, since it controls what is kept.

Role 5

Logging Admin

Full control of logging resources. Keep to a very small group.

Protecting sensitive content

Applications sometimes accidentally write passwords, tokens, card numbers or personal data into logs. Because logs are widely read and copied, this is a serious risk. Avoid logging sensitive values in the first place, mask or hash them before writing, and use tools that detect and redact sensitive data where available. Use log views and separate buckets to limit who can read the most sensitive logs.

Control 1

Encryption

Logs are encrypted at rest and in transit by default. Customer-managed keys are an option for buckets.

Control 2

Data Residency

Choose bucket locations that meet legal requirements before creating them.

Control 3

Service Perimeters

VPC Service Controls reduce the risk of logs being exported outside approved boundaries.

Control 4

Least-Privilege Sinks

Sink writer identities receive only the permission to write to their destination.

ANTI-PATTERN-03 Avoid
Problem

Logging full request bodies, authentication headers or personal data for debugging convenience and leaving it in production.

Why It’s Harmful

Anyone with log access can read secrets and personal data. Logs are copied to other systems, increasing exposure and creating legal obligations.

Correct Approach

Log identifiers and outcomes, not secrets. Mask sensitive fields, use debug-level logs only temporarily, and restrict access to sensitive logs.

14Cost and Pricing

Logging costs are driven mostly by volume. Understanding the meters lets you keep valuable logs and drop the waste.

Cost 1

Ingestion

Billed by the amount of log data ingested into buckets, usually with a free monthly allowance per project. This is typically the main cost.

Cost 2

Storage and Retention

The default retention period is included, while keeping logs longer in buckets is billed per volume per month.

Cost 3

Data Access Audit Logs

These can be very large for busy services and are billed like other logs when enabled.

Cost 4

Exports and Analytics

Sinks to BigQuery, Cloud Storage and Pub/Sub have their own destination charges, and analytics queries may carry charges.

Cost 5

Metrics and Alerts

Log-based metrics and monitoring features have their own pricing, especially with many time series.

Ways to reduce cost without losing value

1

Find the Biggest Producers

Use volume metrics and Log Analytics to see which services and log names produce the most data.

2

Exclude or Sample Noise

Exclude health checks and repetitive debug messages, or keep only a percentage of high-volume entries.

3

Tune Application Log Levels

Run production at info or warning level, and raise detail temporarily when investigating.

4

Right-Size Retention

Keep interactive search for the period you actually use, and archive older data cheaply in Cloud Storage.

5

Be Deliberate with Data Access Logs

Enable them for sensitive services and exempt trusted high-volume accounts where policy allows.

6

Set Budget Alerts

Alert on log volume and billing so a sudden surge is noticed in hours, not at month end.

!
Important

A single misbehaving application stuck in an error loop can generate huge log volumes in minutes. Alert on sudden jumps in ingestion. Prices and free allowances change over time and vary by feature, so check the official Cloud Logging pricing page before budgeting.

15Exporting Logs to Other Tools

Many organizations send logs onward to security, analytics and archival systems.

GoalDestinationReason
Long-term compliance archiveCloud Storage with retention controlsLowest cost for rarely read data kept for years
Deep analysis and reportingBigQuery or Log AnalyticsSQL, joins with business data and dashboards
Security operationsPub/Sub to a security information platformStreaming into detection and investigation tools
Third-party observability platformsPub/Sub or direct integrationsTeams that standardize on another logging product
Central logging projectLog bucket in another projectOne place for operations and security teams to search
Custom processingPub/Sub with a data processing pipelineEnrichment, filtering or routing before storage
flowchart TD
  L[Cloud Logging Log Router] --> A[Log Bucket: Search and Alerts, 30 to 90 days]
  L --> B[BigQuery: Analysis, 1 year]
  L --> C[Cloud Storage: Archive, 7 years]
  L --> D[Pub/Sub: Security Platform]
        
FIG 6 — A tiered design keeps recent logs searchable and older logs cheap
i
Practical Insight

Think of retention in tiers: hot logs for fast search and alerts, warm logs for analysis, and cold logs for compliance. Most investigations need only the last few days, so paying for fast search over years of old data is rarely worthwhile.

!
Common Mistake

Creating a sink and forgetting to grant its writer identity permission on the destination. The sink looks configured, but entries never arrive. After creating a sink, verify that data appears and check for export errors.

16Monitoring and Troubleshooting Logging Itself

When logs go missing, the problem is rarely mysterious. A short checklist solves most cases.

SymptomLikely CauseWhat To Check
No logs from a virtual machineAgent missing, stopped or without permissionAgent status, service account permission to write logs and network access
No logs from a containerApplication not writing to standard output, or logging disabled for the clusterHow the app logs, and cluster logging settings
Logs appear but are unparsed textNot written as structured JSONLog format and parsing configuration
Entries missing in a bucketExclusion filter or sink routingExclusions on the Default sink and sink filters
Sink destination emptyMissing write permission or wrong destinationSink writer identity and destination permissions
Data access logs missingNot enabled for that serviceAudit log configuration
Alert never firesFilter does not match, or metric labels differTest the filter in Logs Explorer and view metric data
Sudden cost spikeNoisy application or newly enabled log categoryIngestion metrics by log name and resource
Truncated or dropped entriesEntries over size limits or write quotas exceededEntry size and write rate
i
Good to Know

Logging services have limits on entry size and write rates. Very large messages may be truncated or rejected, and bursts can hit quotas. Keep entries compact, avoid dumping huge payloads and check current quotas for heavy workloads.

17Cloud Logging Compared with Other Approaches

Several approaches exist for managing logs. Knowing the differences guides your choice.

ApproachWhat It IsBest Fit
Cloud LoggingManaged log collection, storage, search and alerting on Google CloudWorkloads on Google Cloud wanting low-effort, integrated logging
Cloud MonitoringMetrics, dashboards and alertsTrends and health indicators; works alongside logs
BigQuery as a log storeWarehouse used for log analysisHeavy analytics and joins; usually fed from a sink
Third-party logging platformsCommercial or open-source logging productsTeams standardized on a tool across many clouds
Self-managed log stacksSoftware you run yourself for logsSpecial requirements, with the burden of operating it
Security information platformsTools focused on threat detection across sourcesSecurity teams correlating many data sources
Simple Analogy

Logs are the detailed diary of a system; metrics are the dashboard gauges; traces are the route map of one trip. A good operations team uses all three, with the diary providing the explanation once the gauges and the map show where to look.

flowchart TD
  Q1{Running mostly on Google Cloud?} -->|Yes| A1[Start with Cloud Logging]
  Q1 -->|No| Q2{One tool needed across many clouds?}
  Q2 -->|Yes| A2[Consider a multi-cloud platform and forward logs]
  Q2 -->|No| A1
  A1 --> Q3{Need long-term analytics or security detection?}
  Q3 -->|Yes| A3[Add sinks to BigQuery, Storage or Pub/Sub]
  Q3 -->|No| A4[Use buckets, Explorer and alerts]
        
FIG 7 — A simple guide to choosing and extending a logging approach

18Design Patterns and Anti-patterns

Patterns capture what experienced teams repeatedly find works; anti-patterns capture what goes wrong.

Helpful patterns

Structured Logs with Correlation

Every service writes JSON entries with consistent field names, a severity and a trace or request identifier, so searching, metrics and tracing all work together.

Central Logging Project

Aggregated sinks send logs from many projects to a central project, where security and operations teams have tightly controlled access and consistent retention.

Tiered Retention

Recent logs stay in buckets for search and alerts, mid-term logs go to BigQuery for analysis, and long-term records go to Cloud Storage for compliance.

Exclusion and Sampling for Noise

Health checks and repetitive debug lines are excluded or sampled, cutting cost while keeping all errors and warnings.

Log-Based Alerts for Security Events

Rare high-risk events, such as a new owner role or a disabled audit configuration, trigger immediate notifications to the security team.

Views for Team Isolation

One shared bucket serves many teams, each seeing only their own entries through log views, keeping management simple and access safe.

Anti-patterns to avoid

ANTI-PATTERN-04 Avoid
Problem

Logging everything at debug level in production “just in case”.

Why It’s Harmful

Volume and cost soar, real problems drown in noise and performance suffers from excess writing.

Correct Approach

Use sensible default levels, raise detail temporarily during an investigation and remove excessive messages.

ANTI-PATTERN-05 Avoid
Problem

Relying on logs alone to detect problems, with no metrics or alerts built from them.

Why It’s Harmful

Problems are found by customers or by chance, because nobody is watching the logs continuously.

Correct Approach

Turn key patterns into log-based metrics and alerts, and send notifications to the right on-call team.

ANTI-PATTERN-06 Avoid
Problem

Giving everyone broad logging administrator rights so they can fix things themselves.

Why It’s Harmful

People can change or delete sinks, exclusions and retention, accidentally or deliberately hiding evidence and causing data loss.

Correct Approach

Limit configuration roles to a small team, grant viewer access broadly, and alert on logging configuration changes.

19Advantages, Disadvantages and Real-World Uses

An honest view of strengths, limits and where teams actually apply Cloud Logging.

Advantages

  • Fully managed and scalable, with no logging servers to run
  • Automatic collection from many Google Cloud services
  • Powerful search, live tailing and SQL analytics
  • Flexible routing to buckets, BigQuery, Storage and Pub/Sub
  • Built-in audit logging for security and compliance
  • Log-based metrics and alerts for proactive monitoring
  • Tight integration with Trace, Error Reporting and Monitoring

Disadvantages / Trade-offs

  • Costs scale with volume and can surprise unwary teams
  • Excluded logs cannot be recovered later
  • Bucket locations cannot be changed after creation
  • Plain-text logs are hard to analyze reliably
  • Data access audit logs are off by default and must be planned
  • Multi-cloud setups need extra agent and routing work

Real-world examples

E-Commerce Incident Response

An online shop sees checkout errors rise. An alert fires, Error Reporting shows a new exception, a trace identifies a slow payment call, and logs for that trace reveal an expired credential, fixed within minutes.

Bank Audit and Compliance

A bank aggregates audit logs from all projects into a locked central bucket with a multi-year retention, exports a copy to cold storage and alerts on any change to permissions or logging configuration.

Microservices Troubleshooting

A company with dozens of services includes a trace identifier in every log line. Engineers follow one request across services in seconds instead of hunting through separate systems.

Cost Control Program

A platform team uses Log Analytics to find that health checks produce a large share of log volume, excludes them and cuts the logging bill significantly without losing useful information.

Security Threat Hunting

Security analysts query audit logs with SQL to find unusual administrative activity, then stream selected logs to a security platform for correlation with other signals.

20Best Practices and Common Mistakes

A short checklist to carry into every logging project.

Best Practices

  • Use structured JSON logging with consistent field names
  • Include severity and a trace or request identifier in every entry
  • Choose log levels deliberately and avoid debug noise in production
  • Review log volume regularly and exclude or sample what you never read
  • Enable data access audit logs for sensitive services in advance
  • Use aggregated sinks and a protected central project for audit logs
  • Set retention to match need and use tiered storage
  • Turn key patterns into log-based metrics and alerts
  • Use views and least-privilege roles; never log secrets or personal data
  • Alert on logging configuration changes and ingestion spikes

Common Mistakes

  • Plain-text, multi-line, unstructured logs
  • No request identifier to link related entries
  • Excluding logs you later need
  • Assuming data access logs are on by default
  • Keeping everything forever in expensive search storage
  • Logging passwords, tokens or personal data
  • Granting broad logging admin rights
  • Never testing alerts or exports

21Frequently Asked Questions

Q1Do I need to set up Cloud Logging?

The service is enabled by default in Google Cloud projects, and many services send logs automatically. You may need an agent for virtual machines and settings for audit logs, retention and routing.

Q2How long are logs kept?

It depends on the bucket. The Required bucket keeps certain audit logs for a fixed long period, the Default bucket keeps logs for a shorter default period that you can change, and your own buckets can have custom retention.

Q3What is the difference between a sink and a bucket?

A bucket is where logs are stored inside Cloud Logging. A sink is a routing rule that decides which entries go to which destination, which can be a bucket or an outside service.

Q4Are audit logs free?

Admin activity and system event audit logs are generally not charged. Data access audit logs are disabled by default for most services and are billed like other logs when you enable them. Always confirm current pricing.

Q5Why should I use structured logging?

Structured fields let you filter, count and chart by exact values, build reliable metrics and run SQL analysis, which is far harder with free-form text.

Q6How do I reduce my logging bill?

Find the highest-volume sources, exclude or sample low-value entries, lower production log levels, shorten retention for hot storage and archive older logs cheaply.

Q7Can I analyze logs with SQL?

Yes. Log Analytics lets you run SQL over upgraded log buckets, and you can link a BigQuery dataset to query the same logs there.

Q8How do I get alerted when something appears in logs?

Create a log-based metric and alert policy for trends and thresholds, or a log-based alert for rare events that should notify you on the first occurrence.

Q9Can I collect logs from outside Google Cloud?

Yes. Agents and collectors can forward logs from on-premises servers and other clouds, or you can write entries through the API.

Q10How do I let a team see only its own logs?

Use log views on a shared bucket, or separate buckets, and grant each team access to its view with least-privilege roles.

Q11What happens to logs I exclude?

Excluded entries are not stored in that destination and cannot be recovered later, so exclude carefully and consider sampling instead of dropping everything.

Q12How do I follow one request across many services?

Include a trace or request identifier in every log entry. Then filter by that identifier, or open the trace and jump to its related logs.

22Summary and Key Takeaways

Cloud Logging is Google Cloud’s managed flight recorder: it collects log entries from platform services, audit systems, containers, virtual machines and your own code, routes them through the Log Router into buckets and other destinations, and lets you search, analyze with SQL, turn patterns into metrics and alert on important events. Its real power appears when logs are structured, correlated with traces, retained according to need and protected by careful access control. Cost and noise are managed by reviewing volume, excluding or sampling low-value entries, tiering retention and enabling expensive categories such as data access audit logs only where they matter. Treat logging as a designed system, not an afterthought, and review current documentation for limits, features and pricing.

Key Takeaways

  • One central, managed record of everything — Cloud Logging collects logs automatically from many services and via agents, libraries and the API, so you can search across systems in one place.
  • The Log Router controls everything — sinks decide where entries go, exclusions decide what is dropped, and the Required and Default buckets handle built-in routing.
  • Structure and correlate — write JSON logs with severity and trace or request identifiers so search, metrics, traces and Error Reporting work together.
  • Search and analyze — use Logs Explorer for incidents and Log Analytics with SQL for trends, security hunting and cost insight.
  • Turn logs into action — log-based metrics and alerts tell the right people when patterns appear, instead of waiting for someone to read logs.
  • Plan audit logging in advance — admin activity logs are automatic, but data access logs must be enabled before you need them; centralize and protect them.
  • Control cost, access and sensitivity — exclude or sample noise, tier retention, use views and least-privilege roles, never log secrets, and check current pricing and limits.