---
title: "Set up Azure Database for PostgreSQL | Database Observability documentation"
description: "Set up Database Observability for Azure Database for PostgreSQL using Grafana Alloy and send telemetry to Grafana Cloud."
---

> For a curated documentation index, see [llms.txt](/llms.txt). For the complete documentation index, see [llms-full.txt](/llms-full.txt).

# Set up Azure Database for PostgreSQL

Set up Database Observability with Grafana Cloud to collect telemetry from Azure Database for PostgreSQL Flexible Server using Grafana Alloy. You configure your Azure PostgreSQL server 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 Azure PostgreSQL server parameters 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 Azure PostgreSQL has three steps:

1. [**Set up your database**](#set-up-your-database): Prepare your Azure PostgreSQL server so Alloy can collect from it.
2. [**Configure Grafana Alloy**](#configure-grafana-alloy): Configure how Alloy collects telemetry and sends it to Grafana Cloud. Azure PostgreSQL supports a few methods to choose from.
3. [**Verify telemetry in Grafana Cloud**](#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:

- An Azure Database for PostgreSQL Flexible Server 14.0 or later server.
- Permission to modify server parameters.
- Permission to restart the Azure PostgreSQL server if parameter changes require it.
- A PostgreSQL admin user that can create users and grant privileges.
- A planned [Grafana Alloy](/docs/grafana-cloud/observe-and-act/send-data/alloy/) deployment location with network access to your Azure PostgreSQL server endpoint.

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

> 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 Azure PostgreSQL Flexible Server 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 server parameters

Enable `pg_stat_statements` and configure query tracking by adding server parameters to your Azure Database for PostgreSQL Flexible Server. These parameters require a server restart to take effect.

#### Required server parameters

Expand table

| Parameter                   | Value                | Notes            |
|-----------------------------|----------------------|------------------|
| `shared_preload_libraries`  | `pg_stat_statements` | Requires restart |
| `pg_stat_statements.track`  | `all`                | Requires restart |
| `track_activity_query_size` | `4096`               | Requires restart |

#### Use the Azure portal

1. Open the **Azure Portal** and navigate to **Azure Database for PostgreSQL flexible servers**.
2. Select your PostgreSQL flexible server.
3. In the left menu under **Settings**, select **Server parameters**.
4. Search for and configure each parameter listed above.
5. Click **Save** to apply the changes.
6. Some parameters require a server restart. Navigate to **Overview** and click **Restart** if prompted.

For detailed portal instructions, refer to [Configure server parameters](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/how-to-configure-server-parameters-using-portal) in the Azure documentation.

#### Use Terraform

Using Terraform with `azurerm_postgresql_flexible_server_configuration`:

hcl ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```hcl
resource "azurerm_postgresql_flexible_server_configuration" "shared_preload_libraries" {
  name      = "shared_preload_libraries"
  server_id = azurerm_postgresql_flexible_server.main.id
  value     = "pg_stat_statements"
}

resource "azurerm_postgresql_flexible_server_configuration" "pg_stat_statements_track" {
  name      = "pg_stat_statements.track"
  server_id = azurerm_postgresql_flexible_server.main.id
  value     = "all"
}

resource "azurerm_postgresql_flexible_server_configuration" "track_activity_query_size" {
  name      = "track_activity_query_size"
  server_id = azurerm_postgresql_flexible_server.main.id
  value     = "4096"
}
```

Alternatively, configure parameters using the Azure CLI:

Bash ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```bash
az postgres flexible-server parameter set \
  --resource-group <RESOURCE_GROUP> \
  --server-name <SERVER_NAME> \
  --name shared_preload_libraries \
  --value pg_stat_statements

az postgres flexible-server parameter set \
  --resource-group <RESOURCE_GROUP> \
  --server-name <SERVER_NAME> \
  --name pg_stat_statements.track \
  --value all

az postgres flexible-server parameter set \
  --resource-group <RESOURCE_GROUP> \
  --server-name <SERVER_NAME> \
  --name track_activity_query_size \
  --value 4096
```

Replace the placeholders:

- `RESOURCE_GROUP`: Azure resource group name.
- `SERVER_NAME`: Azure PostgreSQL Flexible Server name.

> Note
> 
> The `shared_preload_libraries` parameter requires a server restart. Restart the server after applying the change.

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

SQL ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```sql
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
```

Verify the extension is installed:

SQL ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```sql
SELECT * FROM pg_stat_statements LIMIT 1;
```

### Create a monitoring user and grant required privileges

Connect to your Azure PostgreSQL Flexible Server as an administrator and create the monitoring user:

Create the `db-o11y` user and grant base privileges:

SQL ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```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 *&lt;DB\_O11Y\_PASSWORD&gt;* with a secure password for the `db-o11y` PostgreSQL user.

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

SQL ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```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 ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```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 ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```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 ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```sql
GRANT pg_read_all_data TO "db-o11y";
```

### Verify server parameter settings

Verify that the parameter settings were applied correctly after restarting:

SQL ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```sql
SHOW pg_stat_statements.track;
```

Expected result: Value is `all`.

SQL ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```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` is in `shared_preload_libraries` and the extension is created (`SELECT * FROM pg_stat_statements LIMIT 1;` runs without error).
- `pg_stat_statements.track` is `all` and `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 parameter changes that required a restart have been applied and the server restart is complete.

After these checks pass, your Azure PostgreSQL server is ready for Database Observability. Next, configure Alloy so it can collect telemetry from the server endpoint 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)**](#option-1-configure-alloy-from-the-database-observability-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**](#option-2-configure-alloy-with-the-grafana-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)**](#option-3-configure-alloy-with-a-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.17.0` or later is required for Database Observability. Find the latest stable version on [Docker Hub](https://hub.docker.com/r/grafana/alloy/tags). To update, refer to the [Alloy release notes](https://github.com/grafana/alloy/releases).

> Note
> 
> New to Alloy?
> 
> [Grafana Alloy](/docs/grafana-cloud/observe-and-act/send-data/alloy/introduction/) 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](/docs/grafana-cloud/observe-and-act/send-data/alloy/set-up/install/) before you continue.

### Option 1: Configure Alloy from the Database Observability Configuration page (recommended)

Start here for most deployments. The Configuration page (**Configuration** &gt; **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](/docs/grafana-cloud/send-data/fleet-management/introduction/).
- **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 the configuration method that matches how you manage Alloy.

For an overview of setup methods and what appears in the **Setup** tab, refer to [Configure Alloy from the Configuration page](/docs/grafana-cloud/monitor-applications/database-observability/configure/fleet-management-integration/).

### 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. The Database Observability setup flow generates chart values, and you apply them with your normal Helm workflow.

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

YAML ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
integrations:
  collector: alloy-singleton
  postgresql:
    instances:
      - name: <INSTANCE_NAME>
        jobLabel: integrations/db-o11y
        exporter:
          dataSource:
            host: <SERVER_FQDN>
            port: 5432
            database: postgres
            auth:
              usernameKey: <DB_USERNAME_SECRET_KEY>
              passwordKey: <DB_PASSWORD_SECRET_KEY>
            sslmode: require
          autoDiscovery:
            enabled: true
            databaseDenyList: ["azure_sys", "azure_maintenance"]
          collectors:
            statStatements:
              enabled: true
              excludeUsers: ["db-o11y"]
              excludeDatabases: ["azure_sys", "azure_maintenance"]
        databaseObservability:
          enabled: true
          cloudProvider:
            azure:
              resourceGroup: "<AZURE_RESOURCE_GROUP>"
              serverName: "<AZURE_SERVER_NAME>"
              subscriptionId: "<AZURE_SUBSCRIPTION_ID>"
        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.
- `SERVER_FQDN`: Azure PostgreSQL server fully qualified domain name.
- `AZURE_RESOURCE_GROUP`: Azure resource group for your PostgreSQL Flexible Server.
- `AZURE_SERVER_NAME`: Azure server name for your PostgreSQL Flexible Server.
- `AZURE_SUBSCRIPTION_ID`: Azure subscription ID for your PostgreSQL Flexible Server.
- `DB_USERNAME_SECRET_KEY`: Kubernetes secret key containing database user.
- `DB_PASSWORD_SECRET_KEY`: Kubernetes secret key containing database password.
- `SECRET_NAME`: Name of the Kubernetes secret containing database credentials.
- `NAMESPACE`: Kubernetes namespace where the secret exists.

If you use the External Secrets example below, set `SECRET_NAME` to the generated `ExternalSecret` name, for example `<SERVER_NAME>-db-monitoring-secret`.

To see the full set of values, refer to the k8s-monitoring Helm chart [documentation](https://github.com/grafana/k8s-monitoring-helm/blob/main/charts/k8s-monitoring/charts/feature-integrations/docs/integrations/postgresql.md#database-observability) or the [example configuration](https://github.com/grafana/k8s-monitoring-helm/tree/main/charts/k8s-monitoring/docs/examples/features/database-observability/postgresql).

#### Configure Azure Key Vault and Kubernetes (optional)

If you use Azure Key Vault with External Secrets Operator to manage database credentials, configure them as follows.

##### Secret naming convention

Store monitoring credentials in Azure Key Vault with a name following this convention:

![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```none
postgres-<SERVER_NAME>-monitoring
```

##### PostgreSQL secret format

Store the secret as JSON with the following format:

JSON ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```json
{
  "username": "db-o11y",
  "password": "<DB_O11Y_PASSWORD>",
  "host": "<SERVER_FQDN>",
  "port": 5432,
  "database": "postgres"
}
```

Replace the placeholders:

- `DB_O11Y_PASSWORD`: Password for the `db-o11y` PostgreSQL user.
- `SERVER_FQDN`: Azure PostgreSQL server fully qualified domain name.

##### Create the secret with the Azure CLI

Bash ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```bash
az keyvault secret set \
  --vault-name <KEY_VAULT_NAME> \
  --name "postgres-<SERVER_NAME>-monitoring" \
  --value '{"username":"db-o11y","password":"<DB_O11Y_PASSWORD>","host":"<SERVER_FQDN>","port":5432,"database":"postgres"}'
```

##### Kubernetes External Secrets configuration

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

YAML ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
---
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: <SERVER_NAME>-db-monitoring-secretstore
spec:
  provider:
    azurekv:
      tenantId: <AZURE_TENANT_ID>
      vaultUrl: https://<KEY_VAULT_NAME>.vault.azure.net
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: <SERVER_NAME>-db-monitoring-secret
spec:
  refreshInterval: 1h
  secretStoreRef:
    kind: SecretStore
    name: <SERVER_NAME>-db-monitoring-secretstore
  dataFrom:
    - extract:
        key: postgres-<SERVER_NAME>-monitoring
```

Replace the placeholders:

- `SERVER_NAME`: Azure PostgreSQL server name.
- `AZURE_TENANT_ID`: Azure tenant ID.
- `KEY_VAULT_NAME`: Azure Key Vault name.

### 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 Azure PostgreSQL configuration blocks

Add these blocks to Alloy for Azure Database for PostgreSQL. Replace *&lt;DB\_NAME&gt;*. Create a `local.file` with the Data Source Name string, for example, `"postgresql://<DB_USER>:<DB_PASSWORD>@<SERVER_FQDN>:<DB_PORT>/<DB_DATABASE>?sslmode=require"`:

Alloy ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```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"]
    exclude_databases = ["azure_sys", "azure_maintenance"]
  }

  autodiscovery {
    enabled = true

    // Exclude Azure managed-service databases.
    database_denylist = ["azure_sys", "azure_maintenance"]
  }
}

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"]

  cloud_provider {
    azure {
      resource_group  = "<AZURE_RESOURCE_GROUP>"
      subscription_id = "<AZURE_SUBSCRIPTION_ID>"
      server_name     = "<AZURE_SERVER_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).
- `AZURE_RESOURCE_GROUP`: Azure Resource Group for your PostgreSQL Flexible Server.
- `AZURE_SUBSCRIPTION_ID`: Azure Subscription ID for your PostgreSQL Flexible Server.
- `AZURE_SERVER_NAME`: Azure Server Name for your PostgreSQL Flexible Server (optional).
- `INSTANCE_LABEL`: Value that sets the `instance` label on logs and metrics (optional).
- Secret file content example: `"postgresql://DB_USER:DB_PASSWORD@SERVER_FQDN: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.
  - `SERVER_FQDN`: Azure PostgreSQL server fully qualified domain name (for example, `<SERVER_NAME>.postgres.database.azure.com`).
  - `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](/docs/grafana-cloud/send-data/alloy/reference/components/database_observability/database_observability.postgres/) documentation.

The `cloud_provider` block integrates Database Observability with [Cloud Provider Observability](/docs/grafana-cloud/monitor-infrastructure/monitor-cloud-provider/). To navigate between query performance and Azure infrastructure metrics, refer to [Preconfigured dashboards and alerts for Azure metrics](/docs/grafana-cloud/monitor-infrastructure/monitor-cloud-provider/azure/azure-alerts/#access-database-observability).

#### 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 Azure server parameters:

1. Open the **Azure Portal** and navigate to **Azure Database for PostgreSQL flexible servers**.
2. Select your PostgreSQL flexible server.
3. In the left menu under **Settings**, select **Server parameters**.
4. Search for `log_line_prefix` and set it to: `%m:%r:%u@%d:[%p]:%l:%e:%s:%v:%x:%c:%q%a:`
5. Click **Save** to apply the changes.

Alternatively, use the Azure CLI:

Bash ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```bash
az postgres flexible-server parameter set \
  --resource-group <RESOURCE_GROUP> \
  --server-name <SERVER_NAME> \
  --name log_line_prefix \
  --value '%m:%r:%u@%d:[%p]:%l:%e:%s:%v:%x:%c:%q%a:'
```

> Note
> 
> Ensure [Azure Diagnostic Settings](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/how-to-configure-and-access-logs) are configured to export PostgreSQL logs (`PostgreSQLLogs` category) to an Azure Event Hub.

##### Azure Event Hubs credentials

The `loki.source.azure_event_hubs` component requires an Event Hub connection string and a fully qualified namespace. Configure with:

- Environment variables passed to the Alloy container
- Kubernetes secrets mounted as environment variables
- Azure Managed Identity (when running in Azure Kubernetes Service)

The Event Hub shared access policy must have at least **Listen** permission. You can find the connection string in the Azure Portal under your Event Hub namespace &gt; **Shared access policies**.

##### Add logs processing configuration

Add the logs processing configuration block with [`loki.source.azure_event_hubs`](/docs/grafana-cloud/observe-and-act/send-data/alloy/reference/components/loki/loki.source.azure_event_hubs/). Replace *&lt;DB\_NAME&gt;* (matching the database name used in the main configuration above), *&lt;AZURE\_EVENTHUB\_NAMESPACE&gt;*, *&lt;AZURE\_EVENTHUB\_NAME&gt;*, *&lt;AZURE\_EVENTHUB\_CONNECTION\_STRING&gt;*, and *&lt;INSTANCE\_LABEL&gt;*:

Alloy ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```alloy
// Read logs from Azure Event Hubs
loki.source.azure_event_hubs "postgres_logs_<DB_NAME>" {
  fully_qualified_namespace = "<AZURE_EVENTHUB_NAMESPACE>"
  event_hubs                = ["<AZURE_EVENTHUB_NAME>"]

  authentication {
    mechanism         = "connection_string"
    connection_string = "<AZURE_EVENTHUB_CONNECTION_STRING>"
  }

  forward_to = [loki.process.postgres_azure_logs_<DB_NAME>.receiver]
}

// Parse the Azure JSON log envelope and extract the PostgreSQL message
loki.process "postgres_azure_logs_<DB_NAME>" {
  stage.json {
    expressions = {
      "category"   = "category",
      "pg_message" = "properties.message",
    }
  }

  stage.output {
    source = "pg_message"
  }

  stage.static_labels {
    values = {
      "instance" = "<INSTANCE_LABEL>",
      "job"      = "integrations/db-o11y",
    }
  }

  forward_to = [database_observability.postgres.postgres_<DB_NAME>.logs_receiver]
}
```

Replace the placeholders:

- `DB_NAME`: Database name Alloy uses in component identifiers (must match the `<DB_NAME>` used in the main configuration above).
- `AZURE_EVENTHUB_NAMESPACE`: Fully qualified Event Hub namespace (for example, `my-namespace.servicebus.windows.net`).
- `AZURE_EVENTHUB_NAME`: Name of the Event Hub that receives PostgreSQL diagnostic logs.
- `AZURE_EVENTHUB_CONNECTION_STRING`: Connection string for the Event Hub shared access policy with Listen permission.
- `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 ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```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](/docs/grafana-cloud/monitor-applications/database-observability/configure/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 firewall rules, virtual network settings, DNS, and the monitoring user’s host restrictions.

For detailed guidance, refer to [Troubleshoot Alloy](/docs/grafana-cloud/monitor-applications/database-observability/troubleshoot/alloy/) or [Troubleshoot PostgreSQL](/docs/grafana-cloud/monitor-applications/database-observability/troubleshoot/postgres/).

## Next steps

- [View query performance](/docs/grafana-cloud/monitor-applications/database-observability/monitor/view-query-performance/)
- [Find your application’s queries](/docs/grafana-cloud/monitor-applications/database-observability/monitor/find-application-queries/)
- [Link traces and queries](/docs/grafana-cloud/monitor-applications/database-observability/monitor/link-traces/)
- [Analyze explain plans](/docs/grafana-cloud/monitor-applications/database-observability/investigate/analyze-explain-plans/)
