# Cloud Monitoring and Logging A notification channel, an alert on a metric, a log-based metric and a log sink. - An alert policy needs `combiner` and at least one `conditions` block. A threshold condition's `filter` must name both a `metric.type` and a `resource.type`. - Every `aggregations` block needs an `alignment_period` of at least `"60s"` and a `per_series_aligner` that fits the metric kind: `ALIGN_RATE` or `ALIGN_DELTA` for a delta or cumulative metric, `ALIGN_MEAN` or `ALIGN_MAX` for a gauge. - A log-based metric's name is used in an alert filter as `logging.googleapis.com/user/NAME`. - A sink's writer identity needs a grant on the destination, or nothing arrives. ```hcl variable "project_id" { type = string description = "Project to deploy into." } variable "region" { type = string description = "Region for regional resources." } variable "alert_email" { type = string description = "Address alerts are sent to." } resource "google_monitoring_notification_channel" "email" { project = var.project_id display_name = "Operations email" type = "email" labels = { email_address = var.alert_email } } resource "google_monitoring_alert_policy" "server_errors" { project = var.project_id display_name = "Cloud Run 5xx responses" combiner = "OR" conditions { display_name = "5xx rate above 1 per second for 5 minutes" condition_threshold { filter = "resource.type = \"cloud_run_revision\" AND metric.type = \"run.googleapis.com/request_count\" AND metric.labels.response_code_class = \"5xx\"" comparison = "COMPARISON_GT" threshold_value = 1 duration = "300s" aggregations { alignment_period = "60s" per_series_aligner = "ALIGN_RATE" cross_series_reducer = "REDUCE_SUM" group_by_fields = ["resource.labels.service_name"] } trigger { count = 1 } } } notification_channels = [google_monitoring_notification_channel.email.name] alert_strategy { auto_close = "1800s" } documentation { content = "The service is returning server errors. Check the latest revision's logs." mime_type = "text/markdown" } } resource "google_logging_metric" "rejected_signatures" { project = var.project_id name = "rejected_signatures" filter = "resource.type = \"cloud_run_revision\" AND jsonPayload.event = \"signature_rejected\"" metric_descriptor { metric_kind = "DELTA" value_type = "INT64" unit = "1" } } resource "google_storage_bucket" "audit_logs" { project = var.project_id name = "${var.project_id}-audit-logs" location = var.region uniform_bucket_level_access = true } resource "google_logging_project_sink" "audit" { project = var.project_id name = "audit-to-storage" destination = "storage.googleapis.com/${google_storage_bucket.audit_logs.name}" filter = "logName:\"cloudaudit.googleapis.com\"" unique_writer_identity = true } resource "google_storage_bucket_iam_member" "sink_writes" { bucket = google_storage_bucket.audit_logs.name role = "roles/storage.objectCreator" member = google_logging_project_sink.audit.writer_identity } ```