Grafana Cloud

Set up Google Cloud SQL for PostgreSQL

Set up Database Observability with Grafana Cloud to collect telemetry from Google Cloud SQL for PostgreSQL instances using Grafana Alloy. You configure your Cloud SQL instance and Alloy to forward telemetry to Grafana Cloud.

If you already use the PostgreSQL integration, Database Observability extends it with query-level telemetry collected by the database_observability.postgres Alloy component.

What you’ll achieve

In this article, you:

  • Configure Google Cloud SQL for PostgreSQL database flags for monitoring.
  • Create monitoring users with required privileges.
  • Configure Alloy with the Database Observability components.
  • Forward telemetry to Grafana Cloud.
  • Verify that telemetry appears in Database Observability.

Setup steps

Setting up Database Observability for Cloud SQL for PostgreSQL has three steps:

  1. Set up your database: Prepare your Cloud SQL instance so Alloy can collect from it.
  2. Configure Grafana Alloy: Configure how Alloy collects telemetry and sends it to Grafana Cloud. Cloud SQL supports a few methods to choose from.
  3. Verify telemetry in Grafana Cloud: Check telemetry status and confirm that query metrics appear in Database Observability.

Before you begin

To complete this setup, you need:

  • A Cloud SQL for PostgreSQL 14.0 or later instance.
  • Permission to modify Cloud SQL instance database flags.
  • Permission to restart the Cloud SQL instance if flag changes require it.
  • A PostgreSQL admin user that can create users and grant privileges.
  • A planned Grafana Alloy deployment location with network access to the Cloud SQL instance by using private IP, public IP with authorized networks, or Cloud SQL Auth Proxy.

Estimated setup time: 20-40 minutes, excluding any required maintenance window for restarting the instance.

Note

Alloy should connect directly to the database host. Avoid connecting Alloy to the database through a load balancer or connection pooler such as PgBouncer as it would limit Alloy’s ability to collect accurate telemetry.

Set up your database

In this step, you’ll prepare your Cloud SQL for PostgreSQL instance for monitoring by enabling pg_stat_statements, creating a monitoring user, and granting the permissions Database Observability needs.

Complete this before configuring Alloy. Without it, Alloy can connect to your database, but it won’t be able to collect the telemetry required for Database Observability.

Configure database flags

Enable pg_stat_statements and configure query tracking by adding database flags to your Cloud SQL for PostgreSQL instance. These flags require an instance restart to take effect.

Required database flags

FlagValueNotes
pg_stat_statements.trackallRequires restart
track_activity_query_size4096Requires restart

Use the Google Cloud console

  1. Open the Cloud Console and navigate to SQL.
  2. Select your Cloud SQL for PostgreSQL instance.
  3. Click Edit.
  4. Expand Flags section.
  5. Click Add a database flag for each flag listed above.
  6. Set the flag name and value as specified in the table.
  7. Click Save to apply the changes.
  8. The instance restarts automatically to apply the new flags.

For detailed console instructions, refer to Configure database flags in the Google Cloud documentation.

Use Terraform

Using Terraform with google_sql_database_instance:

hcl
resource "google_sql_database_instance" "postgres" {
  name             = "<INSTANCE_NAME>"
  database_version = "POSTGRES_16"
  region           = "<REGION>"
  settings {
    database_flags {
      name  = "pg_stat_statements.track"
      value = "all"
    }
    database_flags {
      name  = "track_activity_query_size"
      value = "4096"
    }
  }
}

Replace the placeholders:

  • INSTANCE_NAME: Your Cloud SQL instance name.
  • REGION: GCP region where the instance is deployed.

Alternatively, configure flags using the gcloud CLI:

Bash
gcloud sql instances patch <INSTANCE_NAME> \
  --pg_stat_statements.track=all,track_activity_query_size=4096

Note

Cloud SQL requires an instance restart after changing database flags. The restart happens automatically when you apply the changes.

After the instance restarts, enable the pg_stat_statements extension in each database you want to monitor:

SQL
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

Verify the extension is installed:

SQL
SELECT * FROM pg_stat_statements LIMIT 1;

Create a monitoring user and grant required privileges

Connect to your Cloud SQL for PostgreSQL instance as an administrator and create the monitoring user:

Create the db-o11y user and grant base privileges:

SQL
CREATE USER "db-o11y" WITH PASSWORD '<DB_O11Y_PASSWORD>';
GRANT pg_monitor TO "db-o11y";
GRANT pg_read_all_stats TO "db-o11y";

Replace <DB_O11Y_PASSWORD> with a secure password for the db-o11y PostgreSQL user.

Verify that the user has the correct privileges to query pg_stat_statements:

SQL
-- run with the `db-o11y` user
SELECT * FROM pg_stat_statements LIMIT 1;

Disable tracking of monitoring user queries

Prevent tracking of queries executed by the monitoring user itself:

SQL
ALTER ROLE "db-o11y" SET pg_stat_statements.track = 'none';

Grant object privileges for detailed data

To allow collecting schema details and table information, connect to each logical database and grant access to each schema.

For example, for a payments database:

SQL
-- switch to the 'payments' database
\c payments

-- grant permissions in the 'public' schema
GRANT USAGE ON SCHEMA public TO "db-o11y";
GRANT SELECT ON ALL TABLES IN SCHEMA public TO "db-o11y";

-- grant permissions in the 'tests' schema
GRANT USAGE ON SCHEMA tests TO "db-o11y";
GRANT SELECT ON ALL TABLES IN SCHEMA tests TO "db-o11y";

Alternatively, if you’re unsure which specific schemas need access, use the predefined role to grant USAGE and SELECT access to all objects:

SQL
GRANT pg_read_all_data TO "db-o11y";

Verify database flag settings

Verify that the parameter settings were applied correctly after restarting:

SQL
SHOW pg_stat_statements.track;

Expected result: Value is all.

SQL
SHOW track_activity_query_size;

Expected result: Value is 4096.

Database setup checkpoint

Continue to Alloy configuration only after these conditions are true:

  • pg_stat_statements.track is all and the extension is created (SELECT * FROM pg_stat_statements LIMIT 1; runs without error).
  • track_activity_query_size is 4096.
  • The db-o11y monitoring user has the required monitoring and object privileges.
  • The db-o11y monitoring user can connect from the network where Alloy will run.
  • Any flag changes that required a restart have been applied and the instance restart is complete.

After these checks pass, your Cloud SQL instance is ready for Database Observability. Next, configure Alloy so it can collect telemetry from the instance and send it to Grafana Cloud.

Configure Grafana Alloy

After you set up your database, choose how to configure Alloy.

Pick one:

  1. Configuration page (recommended): Database Observability generates the Alloy configuration for you. Then let Fleet Management apply it to an enrolled collector, or choose Manual Configuration to download the generated file and deploy it yourself. Best for most teams.
  2. Kubernetes Monitoring Helm chart: Set databaseObservability.enabled in your values.yaml. Best for teams already running Alloy through the k8s-monitoring Helm chart.
  3. Custom configuration file (advanced): Write the Alloy configuration yourself. Best for full control, custom components or relabeling, or environments the other paths don’t cover.

Make sure you’re on a supported Alloy version

Alloy 1.16.0 or later is required for Database Observability. Find the latest stable version on Docker Hub. To update, refer to the Alloy release notes.

Note

New to Alloy?

Grafana Alloy is an open source collector that sends your data to Grafana Cloud. Database Observability needs it to collect metrics and query telemetry from your database.

If you don’t have it installed, refer to Install Grafana Alloy before you continue.

Start here for most deployments. The Configuration page (Configuration > Setup) generates the Alloy configuration for you, then lets you choose how to deploy it:

  • Fleet Management: Grafana Cloud deploys the configuration to an enrolled Alloy collector and manages it for you, so you don’t edit or ship config files by hand. Best if you want to manage collectors centrally and monitor their health from Grafana Cloud. Refer to Introduction to Fleet Management.
  • Manual Configuration: Download the generated configuration and deploy it with your own tooling. Best if you can’t use Fleet Management or you already manage Alloy deployment yourself.

To start the guided setup flow:

  1. Open Database Observability in Grafana Cloud.
  2. Go to Configuration.
  3. Open Setup.
  4. Click Add database.
  5. Select your database engine.
  6. Follow the setup flow and choose Fleet Management or Manual Configuration when prompted.

For an overview of setup methods and what appears in the Setup tab, refer to Configure Alloy from the Configuration page.

Option 2: Configure Alloy with the Grafana Kubernetes Monitoring Helm chart

Use this method if you already manage Alloy with the k8s-monitoring Helm chart. This path configures Alloy outside the Database Observability setup flow in Grafana Cloud.

Extend your values.yaml and set databaseObservability.enabled to true within the PostgreSQL integration.

YAML
integrations:
  collector: alloy-singleton
  postgresql:
    instances:
      - name: <INSTANCE_NAME>
        exporter:
          dataSource:
            host: <INSTANCE_IP>
            port: 5432
            database: postgres
            sslmode: require
            auth:
              usernameKey: username
              passwordKey: password
          collectors:
            statStatements: true
        databaseObservability:
          enabled: true
          extraConfig: |
            exclude_databases = ["cloudsqladmin"]
            cloud_provider {
              gcp {
                connection_name = "<CLOUDSQL_CONNECTION_NAME>"
              }
            }
          collectors:
            queryDetails:
              enabled: true
            querySamples:
              enabled: true
            schemaDetails:
              enabled: true
            explainPlans:
              enabled: true
        secret:
          create: false
          name: <SECRET_NAME>
          namespace: <NAMESPACE>
        logs:
          enabled: true
          labelSelectors:
            app.kubernetes.io/instance: <INSTANCE_NAME>

Replace the placeholders:

  • INSTANCE_NAME: Name for this database instance in Kubernetes.
  • INSTANCE_IP: Cloud SQL instance IP address.
  • CLOUDSQL_CONNECTION_NAME: Cloud SQL instance connection name in project:region:instance format (for example, my-project:us-central1:my-db).
  • SECRET_NAME: Name of the Kubernetes secret containing database credentials.
  • NAMESPACE: Kubernetes namespace where the secret exists.

To see the full set of values, refer to the k8s-monitoring Helm chart documentation or the example configuration.

Configure GCP Secret Manager and Kubernetes (optional)

If you use GCP Secret Manager with External Secrets Operator to manage database credentials, configure them as follows.

Secret path convention

Store monitoring credentials in GCP Secret Manager with a name following this convention:

cloudsql-<INSTANCE_NAME>-monitoring
PostgreSQL secret format

Store the secret as JSON with the following format:

JSON
{
  "username": "db-o11y",
  "password": "<DB_O11Y_PASSWORD>",
  "host": "<INSTANCE_IP>",
  "port": 5432,
  "database": "postgres"
}

Replace the placeholders:

  • DB_O11Y_PASSWORD: Password for the db-o11y PostgreSQL user.
  • INSTANCE_IP: Cloud SQL instance IP address.
Create the secret with the gcloud CLI
Bash
echo '{"username":"db-o11y","password":"<DB_O11Y_PASSWORD>","host":"<INSTANCE_IP>","port":5432,"database":"postgres"}' | \
  gcloud secrets create cloudsql-<INSTANCE_NAME>-monitoring --data-file=-
Kubernetes External Secrets configuration

Use the External Secrets Operator to sync the GCP secret into Kubernetes:

YAML
---
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: <INSTANCE_NAME>-db-monitoring-secretstore
spec:
  provider:
    gcpsm:
      projectID: <GCP_PROJECT_ID>
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: <INSTANCE_NAME>-db-monitoring-secret
spec:
  refreshInterval: 1h
  secretStoreRef:
    kind: SecretStore
    name: <INSTANCE_NAME>-db-monitoring-secretstore
  dataFrom:
    - extract:
        key: cloudsql-<INSTANCE_NAME>-monitoring

Replace the placeholders:

  • INSTANCE_NAME: Cloud SQL instance name.
  • GCP_PROJECT_ID: Google Cloud project ID.

Option 3: Configure Alloy with a custom configuration file (advanced)

Use this method if you manage Alloy configuration outside Grafana Cloud or need custom relabeling. This path configures Alloy outside the Database Observability setup flow in Grafana Cloud.

Add the Cloud SQL for PostgreSQL configuration blocks

Add these blocks to Alloy for Cloud SQL for PostgreSQL. Replace <DB_NAME>. Create a local.file with the Data Source Name string, for example, "postgresql://<DB_USER>:<DB_PASSWORD>@<INSTANCE_IP>:<DB_PORT>/<DB_DATABASE>?sslmode=require":

Alloy
local.file "postgres_secret_<DB_NAME>" {
  filename  = "/var/lib/alloy/postgres_secret_<DB_NAME>"
  is_secret = true
}

prometheus.exporter.postgres "postgres_<DB_NAME>" {
  data_source_names  = [local.file.postgres_secret_<DB_NAME>.content]
  enabled_collectors = ["stat_statements"]

  stat_statements {
    exclude_users      = ["db-o11y", "cloudsqladmin"]
    exclude_databases  = ["cloudsqladmin"]
  }

  autodiscovery {
    enabled = true

    // Exclude the cloudsqladmin database
    database_denylist = ["cloudsqladmin"]
  }
}

database_observability.postgres "postgres_<DB_NAME>" {
  data_source_name  = local.file.postgres_secret_<DB_NAME>.content
  forward_to        = [loki.relabel.database_observability_postgres_<DB_NAME>.receiver]
  targets           = prometheus.exporter.postgres.postgres_<DB_NAME>.targets
  enable_collectors = ["query_details", "query_samples", "schema_details", "explain_plans"]
  exclude_users      = ["db-o11y", "cloudsqladmin"]
  exclude_databases  = ["cloudsqladmin"]

  cloud_provider {
    gcp {
      connection_name = "<CLOUDSQL_CONNECTION_NAME>"
    }
  }
}

loki.relabel "database_observability_postgres_<DB_NAME>" {
  forward_to = [loki.write.logs_service.receiver]

  rule {
    target_label = "instance"
    replacement  = "<INSTANCE_LABEL>"
  }
}

discovery.relabel "database_observability_postgres_<DB_NAME>" {
  targets = database_observability.postgres.postgres_<DB_NAME>.targets

  rule {
    target_label = "job"
    replacement  = "integrations/db-o11y"
  }

  // OPTIONAL: relabel `instance` to `dsn` before overwriting `instance`;
  // the `dsn` label is used in the integration with the knowledge graph
  rule {
    source_labels = ["instance"]
    target_label  = "dsn"
  }
  rule {
    target_label = "instance"
    replacement  = "<INSTANCE_LABEL>"
  }
}

prometheus.scrape "database_observability_postgres_<DB_NAME>" {
  targets    = discovery.relabel.database_observability_postgres_<DB_NAME>.output
  forward_to = [prometheus.remote_write.metrics_service.receiver]
}

Replace the placeholders:

  • DB_NAME: Database name Alloy uses in component identifiers (appears in component names and secret filenames).
  • CLOUDSQL_CONNECTION_NAME: Cloud SQL instance connection name in project:region:instance format (for example, my-project:us-central1:my-db).
  • INSTANCE_LABEL: Value that sets the instance label on logs and metrics (optional).
  • Secret file content example: "postgresql://DB_USER:DB_PASSWORD@INSTANCE_IP:DB_PORT/DB_DATABASE?sslmode=require".
    • DB_USER: Database user Alloy uses to connect (for example, db-o11y).
    • DB_PASSWORD: Password for the database user.
    • INSTANCE_IP: Cloud SQL instance IP address (private or public).
    • DB_PORT: Database port number (default: 5432).
    • DB_DATABASE: Logical database name in the DSN (recommend: use postgres).

Find more about the options supported by the database_observability.postgres component in the reference documentation.

Add processing of PostgreSQL logs (optional)

Add processing of PostgreSQL logs to gather detailed metrics about query and server errors.

The logs collector processes PostgreSQL logs received through the logs_receiver entry point and exports Prometheus metrics for query and server errors.

Configure log_line_prefix

Configure log_line_prefix via Cloud SQL database flags:

  1. Open the Cloud Console and navigate to SQL.
  2. Select your Cloud SQL for PostgreSQL instance.
  3. Click Edit.
  4. Expand Flags section.
  5. Click Add a database flag, set the name to log_line_prefix and the value to %m:%r:%u@%d:[%p]:%l:%e:%s:%v:%x:%c:%q%a:.
  6. Click Save to apply the changes.
  7. The instance restarts automatically to apply the new flag.

Alternatively, use the gcloud CLI:

Bash
gcloud sql instances patch <INSTANCE_NAME> \
  --database-flags log_line_prefix='%m:%r:%u@%d:[%p]:%l:%e:%s:%v:%x:%c:%q%a:'

Note

Ensure a log sink is configured to route PostgreSQL logs (resource.type="cloudsql_database") to a Pub/Sub topic, and that a Pub/Sub subscription exists for Alloy to pull from.

GCP Pub/Sub credentials

The loki.source.gcplog component requires a GCP project ID and a Pub/Sub subscription name. Configure credentials with:

  • Workload Identity (recommended when running in GKE)
  • Service account key file
  • Application Default Credentials

The service account or workload identity must have the roles/pubsub.subscriber IAM role on the Pub/Sub subscription.

Add logs processing configuration

Add the logs processing configuration block with loki.source.gcplog. Replace <DB_NAME> (matching the database name used in the main configuration above), <GCP_PROJECT_ID>, <PUBSUB_SUBSCRIPTION>, and <INSTANCE_LABEL>:

Alloy
// Pull PostgreSQL logs from GCP Pub/Sub
loki.source.gcplog "gcp_logs_<DB_NAME>" {
  pull {
    project_id   = "<GCP_PROJECT_ID>"
    subscription = "<PUBSUB_SUBSCRIPTION>"
    labels = {
      "job" = "integrations/db-o11y",
    }
  }

  relabel_rules = discovery.relabel.gcp_logs_<DB_NAME>.rules
  forward_to    = [database_observability.postgres.postgres_<DB_NAME>.logs_receiver]
}

// Relabel rules to map GCP log metadata to labels
discovery.relabel "gcp_logs_<DB_NAME>" {
  targets = []

  rule {
    source_labels = ["__gcp_logname"]
    target_label  = "logname"
  }
  rule {
    source_labels = ["__gcp_resource_type"]
    target_label  = "resource_type"
  }
  rule {
    source_labels = ["__gcp_resource_labels_database_id"]
    target_label  = "database_id"
  }
  rule {
    replacement  = "<INSTANCE_LABEL>"
    target_label = "instance"
  }
}

Replace the placeholders:

  • DB_NAME: Database name Alloy uses in component identifiers (must match the <DB_NAME> used in the main configuration above).
  • GCP_PROJECT_ID: Google Cloud project ID containing the Pub/Sub subscription.
  • PUBSUB_SUBSCRIPTION: Pub/Sub subscription name that receives PostgreSQL logs from the log sink.
  • INSTANCE_LABEL: Value that sets the instance label on logs (must match the <INSTANCE_LABEL> used in the main configuration above).
Historical Log Processing

The logs collector only processes logs with timestamps after the collector’s start time. This prevents re-counting historical logs when the source component replays old entries.

Behavior:

  • On startup: Skips logs with timestamps before the collector started
  • Relies on the source component features to prevent duplicate log ingestion across restarts

Add Prometheus and Loki write configuration

Add the Prometheus remote write and Loki write configuration. From Grafana Cloud, open your stack to get the URLs and generate API tokens:

Alloy
prometheus.remote_write "metrics_service" {
  endpoint {
    url = sys.env("GCLOUD_HOSTED_METRICS_URL")

    basic_auth {
      password = sys.env("GCLOUD_RW_API_KEY")
      username = sys.env("GCLOUD_HOSTED_METRICS_ID")
    }
  }
}

loki.write "logs_service" {
  endpoint {
    url = sys.env("GCLOUD_HOSTED_LOGS_URL")

    basic_auth {
      password = sys.env("GCLOUD_RW_API_KEY")
      username = sys.env("GCLOUD_HOSTED_LOGS_ID")
    }
  }
}

Replace the placeholders:

  • GCLOUD_HOSTED_METRICS_URL: Your Grafana Cloud Prometheus remote write URL.
  • GCLOUD_HOSTED_METRICS_ID: Your Grafana Cloud Prometheus instance ID (username).
  • GCLOUD_HOSTED_LOGS_URL: Your Grafana Cloud Loki write URL.
  • GCLOUD_HOSTED_LOGS_ID: Your Grafana Cloud Loki instance ID (username).
  • GCLOUD_RW_API_KEY: Grafana Cloud API token with write permissions.

Verify telemetry in Grafana Cloud

After Alloy starts, verify that Database Observability is receiving telemetry.

  1. In Grafana Cloud, open Database Observability.
  2. Go to Configuration.
  3. Select your database instance.
  4. Confirm that telemetry status checks pass.
  5. Open Queries Overview and confirm that query metrics appear.

After telemetry appears, the database instance should be visible and Queries Overview should show query metrics. Additional data such as query samples, wait events, schema details, and explain plans becomes available as Alloy collects it and as the database engine supports it.

Telemetry can take a few minutes to appear. For detailed status checks, refer to Verify telemetry status.

Troubleshoot first-run issues

If data doesn’t appear after setup:

  • If the database instance doesn’t appear in Database Observability, check Alloy connectivity and labels.
  • If telemetry status checks fail, use the Configuration page to identify the failed requirement.
  • If query metrics appear but samples, schema details, or explain plans are missing, check database privileges and pg_stat_statements settings.
  • If Alloy can’t connect to the database, check authorized networks, private IP or Cloud SQL Auth Proxy settings, DNS, and the monitoring user’s host restrictions.

For detailed guidance, refer to Troubleshoot Alloy or Troubleshoot PostgreSQL.

Next steps