Skip to main content
Version: 1.31

Logging

CloudNativePG outputs logs in JSON format directly to standard output, including PostgreSQL logs, without persisting them to storage for security reasons. This design facilitates seamless integration with most Kubernetes-compatible log management tools, including command line ones like stern.

Important

Long-term storage and management of logs are outside the scope of the operator and should be handled at the Kubernetes infrastructure level. For more information, see the Kubernetes Logging Architecture documentation.

Each log entry includes the following fields:

  • level – The log level (e.g., info, notice).
  • ts – The timestamp.
  • logger – The type of log (e.g., postgres, pg_controldata).
  • msg – The log message, or the keyword record if the message is in JSON format.
  • record – The actual record, with a structure that varies depending on the logger type.
  • logging_pod – The name of the pod where the log was generated.
info

If your log ingestion system requires custom field names, you can rename the level and ts fields using the log-field-level and log-field-timestamp flags in the operator controller. This can be configured by editing the Deployment definition of the cloudnative-pg operator.

Cluster Logs​

You can configure the log level for the instance pods in the cluster specification using the logLevel option. Available log levels are: error, warning, info (default), debug, and trace.

Important

Currently, the log level can only be set at the time the instance starts. Changes to the log level in the cluster specification after the cluster has started will only apply to new pods, not existing ones.

Operator Logs​

The logs produced by the operator pod can be configured with log levels, same as instance pods: error, warning, info (default), debug, and trace.

The log level for the operator can be configured by editing the Deployment definition of the operator and setting the --log-level command line argument to the desired value.

PostgreSQL Logs​

Each PostgreSQL log entry is a JSON object with the logger key set to postgres. The structure of the log entries is as follows:

{
"level": "info",
"ts": 1619781249.7188137,
"logger": "postgres",
"msg": "record",
"record": {
"log_time": "2021-04-30 11:14:09.718 UTC",
"user_name": "",
"database_name": "",
"process_id": "25",
"connection_from": "",
"session_id": "608be681.19",
"session_line_num": "1",
"command_tag": "",
"session_start_time": "2021-04-30 11:14:09 UTC",
"virtual_transaction_id": "",
"transaction_id": "0",
"error_severity": "LOG",
"sql_state_code": "00000",
"message": "database system was interrupted; last known up at 2021-04-30 11:14:07 UTC",
"detail": "",
"hint": "",
"internal_query": "",
"internal_query_pos": "",
"context": "",
"query": "",
"query_pos": "",
"location": "",
"application_name": "",
"backend_type": "startup"
},
"logging_pod": "cluster-example-1",
}
info

Internally, the operator uses PostgreSQL's CSV log format. For more details, refer to the PostgreSQL documentation on CSV log format.

PGAudit Logs​

CloudNativePG offers seamless and native support for PGAudit on PostgreSQL clusters.

To enable PGAudit, add the necessary pgaudit parameters in the postgresql section of the cluster configuration.

Important

The PGAudit library must be added to shared_preload_libraries. CloudNativePG automatically manages this based on the presence of pgaudit.* parameters in the PostgreSQL configuration. The operator handles both the addition and removal of the library from shared_preload_libraries.

Additionally, the operator manages the creation and removal of the PGAudit extension across all databases within the cluster.

Important

CloudNativePG executes the CREATE EXTENSION and DROP EXTENSION commands in all databases within the cluster that accept connections.

The following example demonstrates a PostgreSQL Cluster deployment with PGAudit enabled and configured:

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: cluster-example
spec:
instances: 3

postgresql:
parameters:
"pgaudit.log": "all, -misc"
"pgaudit.log_catalog": "off"
"pgaudit.log_parameter": "on"
"pgaudit.log_relation": "on"

storage:
size: 1Gi

The audit CSV log entries generated by PGAudit are parsed and routed to standard output in JSON format, similar to all other logs:

  • .logger is set to pgaudit.
  • .msg is set to record.
  • .record contains the entire parsed record as a JSON object. This structure resembles that of logging_collector logs, with the exception of .record.audit, which contains the PGAudit CSV message formatted as a JSON object.

This example shows sample log entries:

{
"level": "info",
"ts": 1627394507.8814096,
"logger": "pgaudit",
"msg": "record",
"record": {
"log_time": "2021-07-27 14:01:47.881 UTC",
"user_name": "postgres",
"database_name": "postgres",
"process_id": "203",
"connection_from": "[local]",
"session_id": "610011cb.cb",
"session_line_num": "1",
"command_tag": "SELECT",
"session_start_time": "2021-07-27 14:01:47 UTC",
"virtual_transaction_id": "3/336",
"transaction_id": "0",
"error_severity": "LOG",
"sql_state_code": "00000",
"backend_type": "client backend",
"audit": {
"audit_type": "SESSION",
"statement_id": "1",
"substatement_id": "1",
"class": "READ",
"command": "SELECT FOR KEY SHARE",
"statement": "SELECT pg_current_wal_lsn()",
"parameter": "<none>"
}
},
"logging_pod": "cluster-example-1",
}

See the PGAudit documentation for more details about each field in a record.

Other Logs​

All logs generated by the operator and its instances are in JSON format, with the logger field indicating the process that produced them. The possible logger values are as follows:

  • barman-cloud-wal-archive: logs from barman-cloud-wal-archive
  • barman-cloud-wal-restore: logs from barman-cloud-wal-restore
  • initdb: logs from running initdb
  • pg_basebackup: logs from running pg_basebackup
  • pg_controldata: logs from running pg_controldata
  • pg_ctl: logs from running any pg_ctl subcommand
  • pg_rewind: logs from running pg_rewind
  • pgaudit: logs from the PGAudit extension
  • postgres: logs from the postgres instance (with msg distinct from record)
  • wal-archive: logs from the wal-archive subcommand of the instance manager
  • wal-restore: logs from the wal-restore subcommand of the instance manager
  • instance-manager: from the PostgreSQL instance manager

With the exception of postgres, which follows a specific structure, all other logger values contain the msg field with the escaped message that is logged.

Exporting Logs via OpenTelemetry​

Besides writing them to standard output, the operator, the instance manager, and the PgBouncer instance manager of a Pooler can push their logs directly to an OpenTelemetry Collector via OTLP, without a log collector running on every node. This covers every log described in this page, including the logs of the wal-archive and wal-restore subcommands, which the instance manager forwards. The standard output is unchanged.

The export is enabled by setting the OTEL_EXPORTER_OTLP_ENDPOINT (or OTEL_EXPORTER_OTLP_LOGS_ENDPOINT) environment variable, and is configured through the standard OpenTelemetry environment variables, such as OTEL_EXPORTER_OTLP_HEADERS for the authentication headers, OTEL_EXPORTER_OTLP_CERTIFICATE for the CA certificate of the collector, OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES for the identity of the records. The protocol is http/protobuf, usually on port 4318, unless OTEL_EXPORTER_OTLP_PROTOCOL (or OTEL_EXPORTER_OTLP_LOGS_PROTOCOL) is set to grpc, usually on port 4317.

Each component reads these variables from its own environment:

  • the operator, from the environment of its Deployment, for example through the additionalEnv value of the Helm chart;
  • the instances of a Cluster, from the env and envFrom stanzas of its specification, as described in "Environment variables", so that each Cluster can send its logs to its own collector; a change to these stanzas triggers a rolling update of the instances, while a change to the content of a ConfigMap or Secret they refer to takes effect only after a manual rollout, for example with kubectl cnpg restart;
  • the PgBouncer instances of a Pooler, from the environment of the pgbouncer container in its pod template.

For example, the following Cluster exports its logs via gRPC to a collector that uses TLS and requires a bearer token. The settings are in a ConfigMap, the token in a Secret, and the CA certificate of the collector is mounted through the projected volume:

apiVersion: v1
kind: ConfigMap
metadata:
name: otel-exporter
data:
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector.observability.svc:4317
OTEL_EXPORTER_OTLP_PROTOCOL: grpc
OTEL_EXPORTER_OTLP_CERTIFICATE: /projected/otel/ca.crt
---
apiVersion: v1
kind: Secret
metadata:
name: otel-exporter-auth
stringData:
OTEL_EXPORTER_OTLP_HEADERS: Authorization=Bearer%20<token>
---
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: cluster-example
spec:
instances: 3

envFrom:
- configMapRef:
name: otel-exporter
- secretRef:
name: otel-exporter-auth

env:
- name: OTEL_SERVICE_NAME
value: $(CLUSTER_NAME)
- name: OTEL_RESOURCE_ATTRIBUTES
value: k8s.pod.name=$(POD_NAME),k8s.namespace.name=$(NAMESPACE)

projectedVolumeTemplate:
sources:
- secret:
name: otel-collector-ca
items:
- key: ca.crt
path: otel/ca.crt

storage:
size: 1Gi

OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES identify the records with the name of the cluster and of the pod, and are set in env because Kubernetes expands the $(VAR_NAME) references only there: a value read through envFrom is used as it is. The values of OTEL_EXPORTER_OTLP_HEADERS are percent-decoded, hence the %20 in place of the space.

A Pooler can refer to the same ConfigMap and Secret through the envFrom of the pgbouncer container, mounting the CA certificate at the same path with a volume of its pod template.

apiVersion: postgresql.cnpg.io/v1
kind: Pooler
metadata:
name: pooler-example-rw
spec:
cluster:
name: cluster-example
instances: 3
type: rw

template:
spec:
containers:
- name: pgbouncer
envFrom:
- configMapRef:
name: otel-exporter
- secretRef:
name: otel-exporter-auth
env:
- name: K8S_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: K8S_NAMESPACE_NAME
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: OTEL_SERVICE_NAME
value: pooler-example-rw
- name: OTEL_RESOURCE_ATTRIBUTES
value: k8s.pod.name=$(K8S_POD_NAME),k8s.namespace.name=$(K8S_NAMESPACE_NAME)
volumeMounts:
- name: otel-collector-ca
mountPath: /projected/otel
readOnly: true
volumes:
- name: otel-collector-ca
secret:
secretName: otel-collector-ca
items:
- key: ca.crt
path: ca.crt
warning

The export sends the same records as the standard output, including the PostgreSQL and PGAudit entries. They contain the text of the statements, their parameters when PGAudit logs them, and the details of the errors, which can hold passwords or personal data. With the export, they leave the namespace for the endpoint you set. Send them only to a collector you trust, and filter or redact them there if needed.

Always use an https endpoint, with OTEL_EXPORTER_OTLP_CERTIFICATE when the collector uses a private CA. With http or OTEL_EXPORTER_OTLP_INSECURE, the records and the authentication headers travel in clear text. Keep the headers in a Secret that envFrom refers to, as in the example, and not in env: the values of env are visible in the specification of the Cluster and of its Pods.

Each exported record carries the fields of the corresponding JSON entry:

  • ts is the timestamp;
  • msg is the body;
  • level is the severity, with debug and trace both mapped to DEBUG; the PostgreSQL and PGAudit records are always INFO, as their own severity is in record.error_severity;
  • logger is the instrumentation scope, or an attribute when the process sets it as a field, as the instance manager does;
  • error and stacktrace are the exception.message and exception.stacktrace attributes of the OpenTelemetry semantic conventions, with stacktrace becoming code.stacktrace in a record without an error;
  • every other field is an attribute that keeps its structure: the record of a PostgreSQL log entry, for example, is a map with the same keys it has in the JSON entry.

The records are exported in the background, at the log level of the component, in batches that the OTEL_BLRP_* environment variables can tune. When the collector is unreachable or cannot keep up, the records that don't fit in the queue are dropped, so that the export never slows down PostgreSQL; the standard output still contains them. A failed export writes an OpenTelemetry error entry, only to the standard output. Before exiting, each process waits up to five seconds for the queued records to be exported. The only exception is an instance manager that fences itself because the primary lease is about to expire: it exits at once, to stop PostgreSQL in time, and its queued records are not exported. The records written after the wait, such as the last ones of an online upgrade of the instance manager, are only on the standard output.