Skip to main content

GCP Observability Without the Complexity: Logging, Monitoring, and Alerting That Works

Updated 5 min readMarkdown
Part of seriesGCP: The Missing Manual
GCP Observability Without the Complexity: Logging, Monitoring, and Alerting That Works

GCP's observability suite — Cloud Logging, Cloud Monitoring, Cloud Trace — is capable enough to tell you almost anything about your system. The problem isn't capability. It's that the defaults tell you very little, and building something useful requires deliberate choices about what to log, what to measure, and what to alert on.

This post is about those choices. What to set up, what to skip, and how to know when something is wrong before your users do.


Structured Logging: The Foundation

The most important observability decision you make is how you log. Unstructured logs — plain text strings — are searchable but not filterable or aggregatable. Structured logs — JSON with consistent fields — let you query, group, and alert on specific values.

# logging_config.py
import logging
import json
import sys
from contextvars import ContextVar

request_id_var: ContextVar[str] = ContextVar("request_id", default="")

class StructuredFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        log_entry = {
            "severity": record.levelname,
            "message": record.getMessage(),
            "logger": record.name,
            "request_id": request_id_var.get(""),
        }
        # Merge any extra fields passed to the logger
        if hasattr(record, "__dict__"):
            extra = {
                k: v for k, v in record.__dict__.items()
                if k not in logging.LogRecord.__dict__ and not k.startswith("_")
                and k not in ("args", "msg", "message", "levelname", "name",
                              "pathname", "filename", "module", "exc_info",
                              "exc_text", "stack_info", "lineno", "funcName",
                              "created", "msecs", "relativeCreated", "thread",
                              "threadName", "processName", "process", "taskName")
            }
            log_entry.update(extra)
        return json.dumps(log_entry)

def configure_logging():
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(StructuredFormatter())
    root = logging.getLogger()
    root.handlers = [handler]
    root.setLevel(logging.INFO)
# main.py — middleware to set request_id per request
import uuid
from fastapi import Request
from logging_config import request_id_var

@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
    request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
    token = request_id_var.set(request_id)
    response = await call_next(request)
    response.headers["X-Request-ID"] = request_id
    request_id_var.reset(token)
    return response

Cloud Logging automatically parses JSON written to stdout from Cloud Run. The severity field maps to GCP's log severity levels — structured logs appear in the correct severity bucket in the console without any additional configuration.

Usage in services:

import logging
logger = logging.getLogger(__name__)

async def process_order(order_id: str):
    logger.info("order_processing_started", extra={
        "order_id": order_id,
        "stage": "processing",
    })
    # ...
    logger.info("order_processing_complete", extra={
        "order_id": order_id,
        "duration_ms": elapsed_ms,
        "item_count": len(items),
    })

This makes querying straightforward:

# Cloud Logging query — all logs for a specific order
jsonPayload.order_id="ord_12345"

# Slow processing — orders taking over 5 seconds
jsonPayload.duration_ms > 5000
severity="INFO"
resource.type="cloud_run_revision"

Metrics: What to Actually Measure

Cloud Monitoring collects metrics automatically for Cloud Run (request count, latency, instance count, CPU, memory). These are useful baselines. The metrics that tell you whether your application is healthy are the ones you emit yourself.

# metrics.py — custom metrics via Cloud Monitoring API
from google.cloud import monitoring_v3
from google.api import metric_pb2
import time

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{PROJECT_ID}"

def record_order_processed(status: str, duration_ms: float):
    series = monitoring_v3.TimeSeries()
    series.metric.type = "custom.googleapis.com/pulsecart/orders_processed"
    series.metric.labels["status"] = status
    series.resource.type = "cloud_run_revision"
    series.resource.labels["project_id"] = PROJECT_ID

    point = monitoring_v3.Point()
    point.value.int64_value = 1
    now = time.time()
    point.interval.end_time.seconds = int(now)
    series.points = [point]

    client.create_time_series(
        name=project_name,
        time_series=[series]
    )

For most services, four categories of metrics cover the important signal:

Request metrics — rate, latency (p50/p95/p99), error rate. Cloud Run provides these automatically; filter by endpoint and status code.

Business metrics — orders processed per minute, events published per minute, emails sent per hour. These are the metrics that tell you whether the system is doing useful work, not just responding to requests.

Dependency health — Cloud SQL query latency, Pub/Sub publish latency, external API response times. Slow dependencies show up here before they show up in request latency.

Queue depth — Pub/Sub subscription backlog, Cloud Tasks queue size. A growing backlog that isn't draining is an early signal before requests start failing.


Alerting: Less Is More

The most common observability mistake is alerting on too many things. Alert fatigue is real — a team that receives twenty alerts a day learns to ignore them. The goal is alerts that are always actionable and almost always urgent.

Three alert policies cover most production services:

High error rate:

resource.type="cloud_run_revision"
metric.type="run.googleapis.com/request_count"
metric.labels.response_code_class="5xx"

Threshold: error rate > 1% of requests over 5 minutes
Notification: PagerDuty / email

High latency (p95):

metric.type="run.googleapis.com/request_latencies"
metric.labels.percentile="95"

Threshold: p95 > 3000ms over 5 minutes
Notification: email (not pager — latency spikes often self-resolve)

Pub/Sub backlog not draining:

metric.type="pubsub.googleapis.com/subscription/oldest_unacked_message_age"
resource.labels.subscription_id="pulsecart-orders-sub"

Threshold: oldest unacked message > 300 seconds
Notification: PagerDuty

In Terraform:

resource "google_monitoring_alert_policy" "high_error_rate" {
  display_name = "Cloud Run — High Error Rate"
  combiner     = "OR"

  conditions {
    display_name = "5xx error rate > 1%"
    condition_threshold {
      filter          = <<-EOT
        resource.type="cloud_run_revision"
        AND metric.type="run.googleapis.com/request_count"
        AND metric.labels.response_code_class="5xx"
      EOT
      comparison      = "COMPARISON_GT"
      threshold_value = 0.01
      duration        = "300s"

      aggregations {
        alignment_period   = "60s"
        per_series_aligner = "ALIGN_RATE"
      }
    }
  }

  notification_channels = [var.pagerduty_channel_id]
  alert_strategy {
    auto_close = "1800s"
  }
}

Cloud Trace for Latency Debugging

Cloud Trace shows you where latency comes from inside a request. Enable it for Cloud Run with the OpenTelemetry SDK:

# tracing.py
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter

provider = TracerProvider()
provider.add_span_processor(
    BatchSpanProcessor(CloudTraceSpanExporter())
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
async def process_order(order_id: str):
    with tracer.start_as_current_span("process_order") as span:
        span.set_attribute("order_id", order_id)

        with tracer.start_as_current_span("validate_inventory"):
            await validate_inventory(order_id)

        with tracer.start_as_current_span("publish_event"):
            await publish_order_event(order_id)

When a request is slow, Cloud Trace shows you which span took the time — the database query, the LLM call, the Pub/Sub publish. Without tracing, you're guessing.


The Setup That's Worth Doing on Day One

Log structured JSON. Emit at least one business metric (events or requests processed per minute). Set an error rate alert and a queue backlog alert. Enable Cloud Trace.

Everything else — dashboards, SLO monitoring, log-based metrics — is worth adding incrementally as you learn which signals matter for your specific system. The four things above are worth having before you take the first real traffic.

About the author

  • Senior full-stack engineer and engineering lead with 5+ years building cloud-native systems at scale. I write about the things the docs don't cover — GCP, FastAPI, Terraform, event-driven architecture, and AI-powered backends. No hello-world demos.

No comments yet. Be the first to comment.

GCP: The Missing Manual

Part 6 of 6

GCP's documentation covers what each service does. This series covers the decisions the docs don't make for you — which database to pick, when Cloud Run stops being enough, how IAM actually works if you're coming from AWS, and what to monitor before something goes wrong. Six posts for engineers who are already building on GCP and want to understand it more deeply, not a getting-started guide.

Start from the beginningGCP for Engineers Who Know AWS: The Mental Model That Actually HelpsThe first thing that breaks when an AWS engineer starts working on GCP isn't the tooling or the console. It's the assumption that IAM works the same way. On AWS, you attach policies to IAM users, grou