epok
View as Markdown

PostgreSQL

The OpenTelemetry Collector reads PostgreSQL metrics with its PostgreSQL receiver and tails the server log with the filelog receiver, then sends both to Epok over OTLP/HTTP. Run it on the database host or next to it. Tested with PostgreSQL 16 over TLS (CA-verified) and with a streaming replica and collector 0.162.0.

1. Create a monitoring user

The pg_monitor role reads the statistics views and nothing else. Connect to every database you want covered (an empty databases: list means all of them).

bash
read -rsp 'Monitoring password: ' P; echo
psql -U postgres -v pw="$P" <<'SQL'
CREATE USER epok_monitor WITH PASSWORD :'pw';
GRANT pg_monitor TO epok_monitor;
SQL
unset P

2. Turn on the logs you want

The config reads the server log written by logging_collector. Statements slower than log_min_duration_statement are logged with their duration, which the config parses into duration_ms. db_user and db_name come from log_line_prefix: set it to '%m [%p] %q%u@%d ' (the Debian and Ubuntu default) as below. With PostgreSQL's own default '%m [%p] ' the lines still parse, but they carry no db_user or db_name, and the board's slow-statement panel shows one unnamed group.

sql
ALTER SYSTEM SET logging_collector = on;          -- needs a restart
ALTER SYSTEM SET log_min_duration_statement = '500ms';
ALTER SYSTEM SET log_line_prefix = '%m [%p] %q%u@%d ';
SELECT pg_reload_conf();

The collector's user must be able to read the log files. On most installs that means adding it to the database's group. Change the include: paths if your logs live elsewhere.

Personal data: SQL text can contain email addresses, names or tokens. On your host, before anything is sent, every line that carries SQL (slow statements, log_statement lines, STATEMENT and QUERY after an error, DETAIL parameters and prepare) goes through one left-to-right scan: every literal ('…', E'…', U&'…', $$…$$, numbers) becomes ?, comments are dropped, and identifiers and keywords stay. Where the scan cannot be sure where a literal ends (a backslash in a standard string, a $tag$ quote, a nested or unclosed comment, an unclosed quote), it masks the whole rest of the statement. In other lines, everything from the first to the last quote becomes ?, as do email addresses, Key (…)=(…) values and failing rows. Names in a few fixed messages (relation "orders" does not exist, unique constraint "users_email_key", null value in column "email") are kept, so an error still says what failed. A line the parser cannot read (for example under another log_line_prefix) is masked whole except its timestamp and marked redaction:unparsed_line_masked. If a redaction step fails, the collector drops the batch instead of sending it.

3. Run the collector

Install otel/opentelemetry-collector-contrib:0.162.0 (or the matching otelcol-contrib package). Put EPOK_INGEST_KEY (an ingest-only key from Settings, then API Keys) and PG_MONITOR_PASSWORDin the collector's environment file, mode 0600, typed at a prompt that does not echo. Neither goes in the config file or on a command line.

bash
read -rsp 'Epok ingest key: ' K; echo; read -rsp 'Monitoring password: ' P; echo
printf 'EPOK_INGEST_KEY=%s\nPG_MONITOR_PASSWORD=%s\n' "$K" "$P" | sudo tee -a /etc/otelcol-contrib/otelcol-contrib.conf >/dev/null
unset K P
sudo chmod 600 /etc/otelcol-contrib/otelcol-contrib.conf

The connection is TLS with the server certificate verified: set endpoint to the server name in its certificate and ca_file to the CA that signed it. Plain TCP is only for a collector on the database host; the file shows those localhost lines as a comment. The same file is in the app under Connect.

yaml
# otelcol-postgresql.yaml: PostgreSQL metrics + server logs to Epok
# Collector: otel/opentelemetry-collector-contrib:0.162.0 (pinned; tested with PostgreSQL 16)
#
# Secrets never go in this file or on a command line. Put them in the collector's
# environment file (otelcol-contrib package: /etc/otelcol-contrib/otelcol-contrib.conf,
# or an EnvironmentFile= of your own, mode 0600):
#   read -rsp 'Epok ingest key: ' K; echo; read -rsp 'Monitoring password: ' P; echo
#   printf 'EPOK_INGEST_KEY=%s\nPG_MONITOR_PASSWORD=%s\n' "$K" "$P" | sudo tee -a /etc/otelcol-contrib/otelcol-contrib.conf >/dev/null
#   unset K P
#
# Monitoring user (read-only statistics, no table access), password read without echo:
#   read -rsp 'Monitoring password: ' P; echo
#   psql -U postgres -v pw="$P" <<'SQL'
#   CREATE USER epok_monitor WITH PASSWORD :'pw';
#   GRANT pg_monitor TO epok_monitor;
#   SQL
#   unset P

receivers:
  postgresql:
    endpoint: db.example.internal:5432   # the server's name as it appears in its TLS certificate
    transport: tcp
    username: epok_monitor
    password: ${env:PG_MONITOR_PASSWORD}
    databases: []                # empty = every database the user can connect to
    collection_interval: 30s
    tls:
      insecure: false            # TLS on and the server certificate verified
      ca_file: /etc/otelcol-contrib/db-ca.pem   # the CA that signed the server certificate
      # LOCALHOST ONLY (collector on the database host, server without TLS):
      #   endpoint: localhost:5432
      #   tls: {insecure: true}
    metrics:
      postgresql.database.locks: {enabled: true}
      postgresql.deadlocks: {enabled: true}
      postgresql.blks_hit: {enabled: true}
      postgresql.blks_read: {enabled: true}
      postgresql.tup_fetched: {enabled: true}
      postgresql.tup_returned: {enabled: true}
      postgresql.tup_inserted: {enabled: true}
      postgresql.tup_updated: {enabled: true}
      postgresql.tup_deleted: {enabled: true}
      postgresql.temp_files: {enabled: true}
      postgresql.sequential_scans: {enabled: true}
      postgresql.wal.delay: {enabled: true}

  # Server log (logging_collector = on). Slow statements appear when
  # log_min_duration_statement is set, e.g. ALTER SYSTEM SET log_min_duration_statement = '500ms'.
  # db_user and db_name come from log_line_prefix. Set the Debian prefix (a reload is enough):
  #   ALTER SYSTEM SET log_line_prefix = '%m [%p] %q%u@%d '; SELECT pg_reload_conf();
  # With the default prefix '%m [%p] ' lines still parse, without db_user and db_name.
  # Statement text can carry personal data: transform/redact_sql below masks every literal on
  # this host. A line the parser cannot read (another log_line_prefix, a stray continuation
  # line) is masked whole and marked redaction=unparsed_line_masked.
  filelog/postgresql:
    include: [/var/log/postgresql/*.log]
    start_at: end
    multiline:
      # PostgreSQL indents every continuation line of a multi-line message with a tab, so a line
      # that starts with a date at column 0 is always a new entry, whatever log_line_prefix is.
      line_start_pattern: '^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}'
    operators:
      # log_line_prefix '%m [%p] ' (PostgreSQL default) or '%m [%p] %q%u@%d ' (Debian/Ubuntu)
      - type: regex_parser
        regex: '^(?P<pg_prefix>(?P<pg_time>\S+ \S+(?: \S+)?) \[(?P<pg_pid>\d+)\] (?:(?P<db_user>[^@\s]*)@(?P<db_name>\S*) )?(?P<pg_level>[A-Z][A-Z0-9]*):\s+)(?P<message>(?s:.*))$'
        on_error: send
        severity:
          parse_from: attributes.pg_level
          mapping:
            fatal: [FATAL, PANIC]
            error: ERROR
            warn: WARNING
            info: [LOG, INFO, NOTICE, STATEMENT, DETAIL, HINT, CONTEXT, LOCATION, QUERY]
            debug: [DEBUG1, DEBUG2, DEBUG3, DEBUG4, DEBUG5]
      - type: regex_parser
        if: 'attributes.message != nil and attributes.message matches "^duration: "'
        parse_from: attributes.message
        regex: '^duration: (?P<duration_ms>[0-9.]+) ms'
      # Split every line that carries SQL text (log_statement / slow statements: statement:,
      # execute/bind/parse <name>:, STATEMENT and QUERY after an error, DETAIL parameters: and
      # prepare:) into the line head and the SQL, so the SQL goes through the statement scan.
      - type: regex_parser
        if: 'attributes.pg_level in ["STATEMENT", "QUERY"] or (attributes.message != nil and attributes.message matches "^(?:duration: [0-9.]+ ms +)?(?:statement|execute [^:]*|bind [^:]*|parse [^:]*|parameters|prepare): ")'
        parse_from: body
        regex: '^(?P<pg_head>.*?(?: (?:STATEMENT|QUERY):\s+|(?:statement|execute [^:]*|bind [^:]*|parse [^:]*|parameters|prepare): ))(?P<statement>(?s:.*))$'
        on_error: send
      # The body stays the full line ("... FATAL:  password authentication failed ..."), so the
      # database log rules that match on PostgreSQL's own wording keep working; transform/redact_sql
      # rebuilds it from the prefix and the redacted message, then drops both helpers.
      - type: add
        field: attributes.db_system
        value: postgresql

processors:
  batch:
    send_batch_max_size: 10000   # at or under Epok's 10,000 entries per batch
  resourcedetection:
    detectors: [env, system]
    system:
      hostname_sources: [os]
  resource/postgresql:
    attributes:
      - key: service.name
        value: postgresql
        action: upsert
  # Statement text can carry personal data. SQL lines are read by ONE left-to-right scan
  # (standard_conforming_strings semantics): every literal ('…', E'…', U&'…', X'…', $$…$$,
  # numbers, 0x…/0o…/0b…) becomes ?, comments are dropped, identifiers and keywords stay.
  # When the scan cannot be sure where a literal ends (a backslash in a standard string, a
  # $tag$ quote, a nested or unclosed comment, an unclosed quote) it masks the WHOLE rest of
  # the statement. Other lines: the text from the first to the last quote becomes ? (values
  # in PostgreSQL's messages are not escaped, so nothing between quotes is trusted), plus
  # e-mail addresses, Key (…)=(…) values, failing rows, 0x… and numbers of 3+ digits. Names
  # in a few fixed messages (relation "orders" does not exist, unique constraint "…", …)
  # are identifiers and are kept. Input that PostgreSQL echoes after "line N: " (JSON, XML) is masked whole.
  transform/redact_sql:
    error_mode: propagate     # a redaction step that fails drops the batch; nothing is sent unredacted
    log_statements:
      - context: log
        conditions:
          - attributes["statement"] != nil
        statements:
          - 'replace_pattern(attributes["statement"], "(\"(?:[^\"]|\"\")*\")|(?i:\\be)('')(?:[^''\\\\]|\\\\.|'''')*''|(?i:\\b(?:[xbn]|u&))?('')(?:[^''\\\\]|'''')*''|(?i:\\b(?:[xbn]|u&))?('')(?:[^''\\\\]|'''')*\\\\(?s:.*)|(\\$$\\$$)(?s:.*?)\\$$\\$$|(\\$$\\$$)(?s:.*)|(\\$$[A-Za-z_][A-Za-z0-9_]*\\$$)(?s:.*)|(/\\*)(?:[^*]|\\*+[^*/])*/\\*(?s:.*)|/\\*(?:[^*]|\\*+[^*/])*\\*+/|(/\\*)(?s:.*)|--[^\\n]*|(?i:\\be)?('')(?s:.*)|\"(?s:.*)|([A-Za-z_][A-Za-z0-9_$$]*)", "$${1}$${2}$${3}$${4}$${5}$${6}$${7}$${8}$${9}$${10}$${11}")'
          - 'replace_pattern(attributes["statement"], "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", "?")'
          - 'replace_pattern(attributes["statement"], "''|\\$$\\$$|\\$$[A-Za-z_][A-Za-z0-9_]*\\$$|/\\*", "?")'
          - 'replace_pattern(attributes["statement"], "(?i)\\b0x[0-9a-f_]+\\b", "?")'
          - 'replace_pattern(attributes["statement"], "(?i)\\b0[bo][0-7_]+\\b", "?")'
          - 'replace_pattern(attributes["statement"], "\\b\\d[\\d_]*(?:\\.[\\d_]*)?(?:[eE][+-]?\\d+)?\\b", "?")'
          - 'replace_pattern(attributes["statement"], "(?i)\\bIN\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)", "IN (?)")'
          - set(body, Concat([attributes["pg_head"], attributes["statement"]], ""))
      - context: log
        conditions:
          - 'attributes["statement"] == nil and attributes["message"] != nil and not (attributes["pg_level"] == "STATEMENT" or attributes["pg_level"] == "QUERY" or IsMatch(attributes["message"], "^(?:duration: [0-9.]+ ms +)?(?:statement|execute [^:]*|bind [^:]*|parse [^:]*|parameters|prepare): "))'
        statements:
          - 'replace_pattern(attributes["message"], "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", "?")'
          - 'replace_pattern(attributes["message"], "Failing row contains \\((?s:.*)\\)", "Failing row contains (?)")'
          - 'replace_pattern(attributes["message"], "\\)=\\((?s:.*)\\)", ")=(?)")'
          - 'replace_pattern(attributes["message"], "^(relation|table|column|index|sequence|view|type|schema|database|extension|trigger|constraint|cursor|savepoint|prepared statement|function) \"([^\"«»]*)\" (does not exist|already exists)( at character [0-9]+)?$$", "$${1} «$${2}» $${3}$${4}")'
          - 'replace_pattern(attributes["message"], "^column \"([^\"«»]*)\" of relation \"([^\"«»]*)\" (does not exist|already exists)( at character [0-9]+)?$$", "column «$${1}» of relation «$${2}» $${3}$${4}")'
          - 'replace_pattern(attributes["message"], "^column reference \"([^\"«»]*)\" is ambiguous( at character [0-9]+)?$$", "column reference «$${1}» is ambiguous$${2}")'
          - 'replace_pattern(attributes["message"], "^duplicate key value violates unique constraint \"([^\"«»]*)\"$$", "duplicate key value violates unique constraint «$${1}»")'
          - 'replace_pattern(attributes["message"], "^null value in column \"([^\"«»]*)\" of relation \"([^\"«»]*)\" violates not-null constraint$$", "null value in column «$${1}» of relation «$${2}» violates not-null constraint")'
          - 'replace_pattern(attributes["message"], "^new row for relation \"([^\"«»]*)\" violates check constraint \"([^\"«»]*)\"$$", "new row for relation «$${1}» violates check constraint «$${2}»")'
          - 'replace_pattern(attributes["message"], "^(insert or update|update or delete) on table \"([^\"«»]*)\" violates foreign key constraint \"([^\"«»]*)\"$$", "$${1} on table «$${2}» violates foreign key constraint «$${3}»")'
          - 'replace_pattern(attributes["message"], "^(update or delete) on table \"([^\"«»]*)\" violates foreign key constraint \"([^\"«»]*)\" on table \"([^\"«»]*)\"$$", "$${1} on table «$${2}» violates foreign key constraint «$${3}» on table «$${4}»")'
          - 'replace_pattern(attributes["message"], "^(Key \\([^\"«»()]*\\)=\\(\\?\\) is not present in table )\"([^\"«»]*)\"\\.$$", "$${1}«$${2}».")'
          - 'replace_pattern(attributes["message"], "(\\bline [0-9]+: )(?s:.*)", "$${1}?")'
          - 'replace_pattern(attributes["message"], "[''\"](?s:.*)[''\"]", "?")'
          - 'replace_pattern(attributes["message"], "[''\"](?s:.*)", "?")'
          - 'replace_pattern(attributes["message"], "(?i)\\b0x[0-9a-f]+\\b", "?")'
          - 'replace_pattern(attributes["message"], "\\b\\d{3,}(?:\\.\\d+)?\\b", "?")'
          - 'replace_pattern(attributes["message"], "«([^«»]*)»", "\"$${1}\"")'
          - set(body, Concat([attributes["pg_prefix"], attributes["message"]], ""))
      # Fail closed: a SQL-bearing line whose SQL could not be split off is masked whole.
      - context: log
        conditions:
          - 'attributes["statement"] == nil and attributes["message"] != nil and (attributes["pg_level"] == "STATEMENT" or attributes["pg_level"] == "QUERY" or IsMatch(attributes["message"], "^(?:duration: [0-9.]+ ms +)?(?:statement|execute [^:]*|bind [^:]*|parse [^:]*|parameters|prepare): "))'
        statements:
          - set(attributes["message"], "?")
          - set(attributes["redaction"], "sql_not_split_masked")
          - set(body, Concat([attributes["pg_prefix"], attributes["message"]], ""))
      # Fail closed: a line the parser could not read keeps only its leading timestamp.
      - context: log
        conditions:
          - attributes["pg_level"] == nil
        statements:
          - 'replace_pattern(body, "^(\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?(?: [A-Z]{2,5})? )?(?s:.*)$$", "$${1}?")'
          - set(attributes["redaction"], "unparsed_line_masked")
      - context: log
        statements:
          - delete_key(attributes, "pg_head")
          - delete_key(attributes, "pg_prefix")
          - delete_key(attributes, "message")

exporters:
  otlphttp/epok:
    metrics_endpoint: https://ingest.epok.cloud/v1/metrics
    logs_endpoint: https://ingest.epok.cloud/v1/logs
    compression: gzip
    encoding: json
    headers:
      x-api-key: ${env:EPOK_INGEST_KEY}

service:
  pipelines:
    metrics:
      receivers: [postgresql]
      processors: [resourcedetection, resource/postgresql, batch]
      exporters: [otlphttp/epok]
    logs:
      receivers: [filelog/postgresql]
      processors: [resourcedetection, resource/postgresql, transform/redact_sql, batch]
      exporters: [otlphttp/epok]

4. Check that data arrives

Metrics arrive within a minute (one point every 30 seconds). In Metrics, search for any of these names:

postgresql_backends, postgresql_connection_max, postgresql_commits, postgresql_rollbacks, postgresql_blks_hit, postgresql_blks_read, postgresql_replication_data_delay, postgresql_deadlocks, postgresql_database_locks, postgresql_db_size

Logs are searchable in Explore with these queries:

  • service:postgresql -record_type:metric duration_ms:*: slow statements with duration_ms, and db_name and db_user when log_line_prefix carries them
  • service:postgresql -record_type:metric level:(error OR fatal): errors, failed logins and crashes
  • service:postgresql -record_type:metric: every server log line (-record_type:metric leaves out the metric points, which are also stored with service:postgresql)

Dashboard

When database boards are on for your workspace, Settings, then Setup, then Quickstarts installs the PostgreSQL board: connections, throughput, latency or slow queries, cache hit ratio, replication and errors. Without it, every metric and log above is searchable and can be charted on your own dashboards.

Limits

  • A string that contains a backslash (such as 'C:\temp') masks the rest of its statement, because where it ends depends on standard_conforming_strings.
  • Replication lag needs a streaming replica connected to the server the collector reads.
  • Per-table metrics are kept per table only up to 200 tables per metric; above that, boards show the per-database total.
  • Log timestamps are the time the collector read the line, within a few seconds of the server time.
  • Managed PostgreSQL services give the collector no log file, and log_line_prefix there is fixed or cannot be set. Log lines you route to Epok from the provider's log service arrive as plain text: no duration_ms, db_name or db_user fields, so the board's slow-statement panel stays empty. Metrics are not affected.
  • With %u in log_line_prefix, the user name of a failed login is sent as db_user, even when the role does not exist.
  • A value written in double quotes in SQL is a column name to PostgreSQL. Its error (column "Alice" does not exist) keeps that name, like every other identifier.
  • No query samples, normalized query statistics or explain plans. Epok reads server metrics and logs only.

OpenTelemetry CollectorAll install guides