3.3. Working with Logs #
- 3.3.1. General Setup
- 3.3.1.1. Configuring the
file_logReceiver- 3.3.1.2. Configuring the
journaldReceiver- 3.3.1.3. Configuring the OTLP Receiver
- 3.3.1.4. Configuring the SQL Query Receiver
- 3.3.1.5. Configuring the
attributes,resource, andfilterProcessors- 3.3.1.6. Configuring the
otlp_httpExporter- 3.3.1.7. Configuring the
kafkaExporter- 3.3.1.8. Setting up a Pipeline
- 3.3.1.2. Configuring the
- 3.3.1.1. Configuring the
- 3.3.2. Use Cases
This section describes the steps required to manage logs.
Important
Log collection in
JSONformat for DBMS instances is not supported in Postgres Pro version 14 and earlier.pgpro-otel-collector may fail to parse timestamps with the
MSKtime zone (for example,2026-08-10 23:14:16.396 MSK). For troubleshooting, refer to Section 5.1.While TLS (Transport Layer Security) is always enabled by default, it is recommended to configure mutual TLS (mTLS). For more details, refer to Section 3.6.4.
3.3.1. General Setup #
3.3.1.1. Configuring the file_log Receiver #
Important
filelog has been renamed to file_log to comply with the component naming convention. The deprecated alias is still supported but produces warnings and will be completely removed in future releases. Update your configuration accordingly.
The file_log receiver is an open-source component of the OpenTelemetry Collector that is used for collecting logs from the DBMS instance. For detailed information about this receiver, refer to the OpenTelemetry documentation.
The file_log receiver should be added to the receivers section and configured.
The receiver configuration depends on the database instance setup and the log format used (see the logging_collector and log_destination parameters). The collector supports log collection in the CSV and JSON formats.
Regardless of the log format, the path to the log directory and the template for log file names need to be specified.
An example of setting up a receiver for collecting logs in the JSON format:
receivers:
file_log:
include: [ /var/log/postgresql/*.json ]
start_at: end
# force_flush_period: 10m
# max_log_size: 20MB
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 30s
max_elapsed_time: 5m
operators:
- type: json_parser
parse_ints: true
timestamp:
parse_from: attributes.timestamp
layout_type: strptime
layout: '%Y-%m-%d %H:%M:%S.%L %Z'
severity:
parse_from: attributes.error_severity
mapping:
debug: [ DEBUG ]
info: [ INFO, NOTICE, LOG ]
warn: [ WARNING ]
error: [ ERROR ]
fatal: [ FATAL, PANIC ]
- type: remove
field: attributes.timestamp
The severity section defines how log severity levels are parsed and categorized based on their importance and urgency. For more information on this parameter, refer to the OpenTelemetry documentation.
You can customize the log entry limits to correctly parse and transmit log entries larger than 16 KB. Use the max_log_size parameter to set the maximum size of a log entry to read. A log entry will be truncated if it is larger than the set value. The default is 1MiB.
The force_flush_period specifies how long to wait after the last new data is found in the file before emitting any remaining partial log entry at the end of the file. The default is 500ms.
For more information about these parameters, refer to the OpenTelemetry documentation.
An example of setting up a receiver for collecting logs in the CVS format:
receivers:
file_log:
include: [ /var/log/postgresql/*.csv ]
start_at: end
# force_flush_period: 10m
# max_log_size: 20MB
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 30s
max_elapsed_time: 5m
multiline:
line_start_pattern: ^[0-9]{4}-[0-9]{2}-[0-9]{2}
operators:
- type: csv_parser
header: timestamp,user,dbname,pid,connection_from,session_id,line_num,ps,session_start,vxid,txid,error_severity,state_code,message,detail,hint,internal_query,internal_position,context,statement,cursor_position,func_name,application_name,backend_type,leader_pid,query_id
timestamp:
parse_from: attributes.timestamp
layout_type: strptime
layout: '%Y-%m-%d %H:%M:%S.%L %Z'
severity:
parse_from: attributes.error_severity
mapping:
debug: [ DEBUG ]
info: [ INFO, NOTICE, LOG ]
warn: [ WARNING ]
error: [ ERROR ]
fatal: [ FATAL, PANIC ]
- type: remove
field: attributes.timestamp
Note
CSV configuration requires specifying more parameters than other formats, as it has to adapt to CSV logging specifics.
A detailed description of configuration parameters with examples can be found in the /usr/share/doc/pgpro-otel-collector/examples directory.
3.3.1.2. Configuring the journald Receiver #
The journald receiver is an open-source component of the OpenTelemetry Collector for gathering logs from the systemd journal, which is particularly useful for Postgres Pro Shardman and Postgres Pro Enterprise Manager(PPEM). For detailed information about this receiver, refer to the OpenTelemetry documentation.
The log_destination parameter in Postgres Pro must be configured to send logs to syslog. For more details on the configuration, refer to the section Error Reporting and Logging.
An example of setting up the journald receiver for sending logs in the journald format to PPEM for PostgreSQL:
receivers:
journald:
directory: /var/log/journal
start_at: end
units:
- postgresql@17-main
operators:
# Rename _PID to pid. This field is required by PPEM
- type: move
id: "pid"
from: body._PID
to: attributes.pid
# Rename __MONOTONIC_TIMESTAMP to line_num. This field is required by PPEM
- type: move
id: "line_num"
from: body.__MONOTONIC_TIMESTAMP
to: attributes.line_num
# Rename MESSAGE to message
- type: move
id: "message"
from: body.MESSAGE
to: attributes.message
# Rename _SYSTEMD_UNIT to backend_type
- type: move
id: "backend_type"
field: attributes.backend_type
from: body._SYSTEMD_UNIT
to: attributes.backend_type
# Transform PRIORITY number to severity text
- type: severity_parser
parse_from: body.PRIORITY
overwrite_text: true
mapping:
debug: [ 7 ] # debug
info: [ 5, 6 ] # notice, info
warn: [ 4 ] # warning
error: [ 3 ] # err
fatal: [ 0, 1, 2 ] # emerg, alert, crit
processors:
batch/journald:
send_batch_size: 4096
timeout: 15s
resource:
attributes:
- action: upsert
key: service.name
value: postgresql
- action: upsert
key: service.instance.id
value: address-of-postgres-instance:5432
attributes/convert:
actions:
- key: pid
action: convert
converted_type: int
- key: line_num
action: convert
converted_type: int
transform:
log_statements:
- context: log
statements:
# Set the error_severity attribute from the severity_text field. This field is required by PPEM
- set(log.attributes["error_severity"], log.severity_text)
# Set the session_start attribute. This field is required by PPEM
- set(log.attributes["session_start"], FormatTime(log.time, "%Y-%m-%d %H:%M:%S %Z"))
# Set the 'session_id' field from _SYSTEMD_INVOCATION_ID or INVOCATION_ID. This field is required by PPEM
- set(log.attributes["session_id"], log.body["_SYSTEMD_INVOCATION_ID"]) where log.body["_SYSTEMD_INVOCATION_ID"] != nil
- set(log.attributes["session_id"], log.body["INVOCATION_ID"]) where (log.attributes["session_id"] == nil and log.body["INVOCATION_ID"] != nil)
exporters:
otlp_http:
endpoint: https://logs.example.org:8080
compression: ""
# tls:
# insecure: false
# ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt
# cert_file: /etc/pgpro-otel-collector/cert.d/client.crt
# key_file: /etc/pgpro-otel-collector/cert.d/client.key
# min_version: "1.3"
headers:
"X-Ppem-Source-Agent-Name": ppem-agent
"X-Ppem-Source-Instance-Port": '5432'
service:
telemetry:
pipelines:
logs:
receivers: [ journald ]
processors: [ resource,attributes/convert,transform,batch/journald ]
exporters: [ otlp_http ]
This receiver can also be used to read Postgres Pro Shardman logs. Below is the example setup for reading such logs and sending them to Elasticsearch.
receivers:
journald:
directory: /var/log/journal
start_at: end
units:
- shardmand@*
operators:
# Parse shardmand message into corresponding log fields
- type: regex_parser
parse_from: body.MESSAGE
regex: '^(?P<timestamp>.+) (?P<level>.+) (?P<message>.*) (?P<fields>.+)$'
timestamp:
parse_from: attributes.timestamp
layout_type: strptime
layout: '%Y-%m-%dT%H:%M:%S.%f%z'
severity:
parse_from: attributes.level
# Parse additional attributes from the 'fields' JSON string
- type: json_parser
parse_from: attributes.fields
# Remove the parsed timestamp to avoid duplication
- type: remove
id: remove_timestamp
field: attributes.timestamp
# Remove the parsed level after severity is extracted
- type: remove
id: remove_level
field: attributes.level
# Remove the parsed 'fields' JSON string after parsing
- type: remove
id: remove_fields
field: attributes.fields
# Retain only fields useful for debugging
- type: retain
fields:
- body._PID
- body._GID
- body._UID
- body._CMDLINE
- body._EXE
- body._HOSTNAME
- body._SYSTEMD_UNIT
- body._TRANSPORT
processors:
batch/journald:
send_batch_size: 4096
timeout: 15s
transform:
log_statements:
- context: log
statements:
# Set resource.process.pid from body._PID, then remove body._PID
- set(resource.attributes["process.pid"], Int(log.body["_PID"]))
- delete_key(log.body, "_PID")
# Set resource.process.command_line from body._CMDLINE (if present), then remove body._CMDLINE
- set(resource.attributes["process.command_line"], log.body["_CMDLINE"]) where log.body["_CMDLINE"] != nil
- delete_key(log.body, "_CMDLINE")
resource:
attributes:
- action: upsert
key: service.name
value: shardmand
- action: upsert
key: service.instance.id
value: address-of-shardman-instance:5432
exporters:
otlp_http:
compression: gzip
endpoint: https://logs.example.org:8080
# tls:
# insecure: false
# ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt
# cert_file: /etc/pgpro-otel-collector/cert.d/client.crt
# key_file: /etc/pgpro-otel-collector/cert.d/client.key
# min_version: "1.3"
service:
pipelines:
logs:
receivers: [ journald ]
processors: [ transform,resource,batch/journald ]
exporters: [ otlp_http ]
3.3.1.3. Configuring the OTLP Receiver #
To collect data in the OpenTelemetry Protocol (OTLP) format over gRPC or HTTP, pgpro-otel-collector uses the otlp receiver — an open-source component of the OpenTelemetry Collector.
To set up the otlp receiver for log collection, follow the example procedure below.
Create the
otlp_receiver.ymlconfiguration file.In the
receivers.otlp.protocolssection of the created configuration file, specify the protocol and its connection parameters.For HTTP:
receivers: otlp: protocols: http: endpoint: 0.0.0.0:4318 max_request_body_size: 20971520 include_metadata: false read_timeout: 0 read_header_timeout: 1m idle_timeout: 1m keep_alives_enabled: true compression_algorithms: ["", "gzip"]Where:
endpointdefines thehost:portcombination on which the receiver listens. Default:.localhost:4318max_request_body_sizecontrols the maximum allowed size of incoming payloads in bytes. Default:20971520(20MiB).include_metadataenables the client metadata propagation from the incoming requests to the downstream consumers. Default:false(disabled).read_timeoutdefines the maximum amount of time allowed for reading the entire request, including the body. A zero or negative value means there will be no timeout. Default:0.read_header_timeoutdefines the maximum amount of time allowed for reading request headers. If zero, theread_timeoutvalue is used. If both are zero, there is no timeout. Default:1m.idle_timeoutdefines the maximum amount of time allowed for waiting for the next request with keepalives enabled (keep_alives_enabled: true). Default:1m.keep_alives_enabledenables HTTP keepalives. Default:true(enabled).compression_algorithmsdefines the list of compression algorithms the server can accept. Default:["", "gzip", "zstd", "zlib", "snappy", "deflate", "lz4"].
For gRPC:
receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 max_recv_msg_size_mib: 16 max_concurrent_streams: 0Where:
endpointdefines thehost:portcombination on which the receiver listens. Default:.localhost:4317max_recv_msg_size_mibcontrols the maximum allowed size of incoming payloads in MiB. Default:4.max_concurrent_streamsdefines the limit for concurrent gRPC streams. If zero (default), there will be no limit.
For HTTP, configure CORS (Cross-Origin Resource Sharing) — a browser security mechanism that allows a server to specify which external origins a browser is allowed to request resources from:
cors: allowed_origins: - http://test.com - https://*.example.com allowed_headers: - Example-Header max_age: 7200Where:
allowed_originsspecifies the list of origins allowed to send requests to the receiver. An origin may contain a wildcard (*).Warning
Do not use a plain wildcard
["*"]— it will be rejected becauseAccess-Control-Allow-Credentialsis enabled.allowed_headersallows CORS requests to include headers outside the default allowlist.max_agesets the value of theAccess-Control-Max-Ageheader — a period of time, in seconds, during which the results of CORS preflight requests can be cached. Default:5.
Configure TLS:
tls: cert_file: /etc/pgpro-otel-collector/cert.d/server.crt key_file: /etc/pgpro-otel-collector/cert.d/server.key client_ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt min_version: "1.3" max_version: "1.3"For details on TLS configuration parameters, refer to Section 3.6.4.
Enable basic authentication:
auth: authenticator: basicauth/otlpFor gRPC, configure keepalive parameters to control connection lifetime, ensuring timely cleanup of dead connections:
keepalive: enforcement_policy: min_time: 5m permit_without_stream: false server_parameters: max_connection_age: 256s max_connection_age_grace: 60s max_connection_idle: 256s time: 5m timeout: 20sWhere:
min_timesets the minimum time the client must wait between keepalive messages. If the client sends messages more frequently than the set value, the server may close the connection. Default:5m.permit_without_streamallows keepalive messages with no active requests. If this parameter is disabled, and the client sends a message without any requests being processed, the server will close the connection. Default:false(disabled).max_connection_agedefines the maximum lifetime of a connection. Once this limit is reached, the server sendsGOAWAYand closes the connection. There is no limit by default.max_connection_age_graceadds an extra grace period aftermax_connection_agebefore forcibly closing the connection. There is no limit by default.max_connection_idledefines how long to keep an idle connection before closing it. There is no limit by default.timedefines how long to wait for activity before sending a keepalive message to the client. If set below1s, a minimum of1sis used. Default:2h.timeoutdefines how long to wait for a response to a keepalive message before closing the connection. Default:20s.
Configure the basic authentication extension:
extensions: basicauth/otlp: htpasswd: inline: | ${env:BASIC_AUTH_USERNAME}:${env:BASIC_AUTH_PASSWORD}For more details on basic authentication, refer to Section 3.6.6.
Configure the exporters, processors, and the service pipeline:
exporters: otlp_http: compression: gzip endpoint: https://otlp.example.org:4318 # tls: # insecure: false # ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt # cert_file: /etc/pgpro-otel-collector/cert.d/client.crt # key_file: /etc/pgpro-otel-collector/cert.d/client.key # min_version: "1.3" processors: batch: send_batch_size: 8192 timeout: 10s service: extensions: [ basicauth/otlp ] pipelines: logs: receivers: [ otlp ] processors: [ batch ] exporters: [ otlp_http ]Start pgpro-otel-collector with the created configuration file along with the main configuration file:
build/pgpro-otel-collector/pgpro-otel-collector --config configs/basic.yml --config configs/otlp_receiver.yml
To support both HTTP and gRPC protocols simultaneously, configure each separately, as shown in the full example below. To disable a protocol, simply omit it from the protocols list.
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
max_request_body_size: 20971520
include_metadata: false
read_timeout: 0
read_header_timeout: 1m
idle_timeout: 1m
keep_alives_enabled: true
compression_algorithms: ["", "gzip"]
cors:
allowed_origins:
- http://test.com
- https://*.example.com
allowed_headers:
- Example-Header
max_age: 7200
tls:
cert_file: /etc/pgpro-otel-collector/cert.d/server.crt
key_file: /etc/pgpro-otel-collector/cert.d/server.key
client_ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt
min_version: "1.3"
max_version: "1.3"
auth:
authenticator: basicauth/otlp
grpc:
endpoint: 0.0.0.0:4317
max_recv_msg_size_mib: 16
max_concurrent_streams: 0
tls:
cert_file: /etc/pgpro-otel-collector/cert.d/server.crt
key_file: /etc/pgpro-otel-collector/cert.d/server.key
client_ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt
min_version: "1.3"
max_version: "1.3"
auth:
authenticator: basicauth/otlp
keepalive:
enforcement_policy:
min_time: 5m
permit_without_stream: false
server_parameters:
max_connection_age: 256s
max_connection_age_grace: 60s
max_connection_idle: 256s
time: 5m
timeout: 20s
extensions:
basicauth/otlp:
htpasswd:
inline: |
${env:BASIC_AUTH_USERNAME}:${env:BASIC_AUTH_PASSWORD}
exporters:
otlp_http:
compression: gzip
endpoint: https://otlp.example.org:4318
# tls:
# insecure: false
# ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt
# cert_file: /etc/pgpro-otel-collector/cert.d/client.crt
# key_file: /etc/pgpro-otel-collector/cert.d/client.key
# min_version: "1.3"
processors:
batch:
send_batch_size: 8192
timeout: 10s
service:
extensions: [ basicauth/otlp ]
pipelines:
logs:
receivers: [ otlp ]
processors: [ batch ]
exporters: [ otlp_http ]
For the full list of the otlp receiver configuration parameters, refer to the OpenTelemetry documentation.
3.3.1.4. Configuring the SQL Query Receiver #
The sqlquery receiver is an open-source component of the OpenTelemetry Collector for gathering metrics and/or logs from custom SQL queries.
Warning
The sqlquery receiver is currently experimental and is not recommended for production use.
To set up the sqlquery receiver for collecting logs, follow the example procedure below.
Create the
sqlquery.ymlconfiguration file.In the created configuration file, specify database connection parameters in the
receivers.sqlquerysection:receivers: sqlquery: driver: postgres host: localhost port: 5432 database: postgres username: postgres password: ${env:POSTGRESQL_PASSWORD} # Additional driver-specific connection parameters additional_params: application_name: pgpro-otel-collector sslmode: disable # The time interval between query executions. Default: 10s collection_interval: 60s # storage: file_storage # Defines setup for the component's own telemetry telemetry: logs: # If true, each executed query is logged at debug level query: false # The maximum number of open connections to the Postgres Pro server. Default: 0 (unlimited) max_open_conn: 5For persistent tracking across the collector restarts, configure a storage extension and reference it with the
storageparameter. For more details, refer to the OpenTelemetry documentation.The
passwordparameter supports environment variable substitution, as shown in the example. Special characters in the credentials are automatically URL-encoded to ensure proper connection string formatting.Alternatively, you can use the
datasourceparameter to provide a complete connection string:datasource: "host=localhost port=5432 user=postgres password=postgres application_name=pgpro-otel-collector sslmode=disable"
Add queries to collect logs. Each query consists of an SQL statement and a
logssection. There may be severallogssections, but at least one such section is required.receivers: sqlquery: ... queries: - sql: SELECT id, message, type FROM my_logs WHERE id > $1 ORDER BY id tracking_start_value: "0" tracking_column: id logs: # Column containing the log message text - body_column: message # Columns to include as log attributes attribute_columns: ["type"]This example assumes the following database schema:
CREATE TABLE my_logs (id INTEGER, message TEXT, type TEXT) ON CONFLICT DO NOTHING; INSERT INTO my_logs VALUES (1, 'message1', 'info'), (2, 'message2', 'info'), (3, 'message3', 'error') ON CONFLICT DO NOTHING;
The
tracking_start_valueparameter defines the initial value for the query parameter ($1), andtracking_columnspecifies which column value to store for subsequent queries. These parameters apply only to log collection.Note
To prevent duplicate log collection across collection intervals, use parameterized queries with the
tracking_start_valueandtracking_columnparameters. Ensure query results are sorted in ascending order by thetracking_columnvalue.Note
Avoid queries that produce NULL values. If a query returns NULL in a column referenced in the configuration, errors will be logged, but the receiver will continue operating.
Configure exporters, processors, and the service pipeline:
... exporters: otlp_http/sqlquery/logs: compression: gzip endpoint: https://logs.example.org:8080 # tls: # insecure: false # # Required for self-signed certificates (system root CAs are used if empty) # ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt # # cert_file/key_file: required for mTLS # cert_file: /etc/pgpro-otel-collector/cert.d/client.crt # key_file: /etc/pgpro-otel-collector/cert.d/client.key # min_version: "1.3" headers: X-Ppem-Source-Agent-Name: local X-Ppem-Source-Instance-Port: '5432' processors: batch/sqlquery: send_batch_size: 2048 timeout: 10s resource: attributes: - key: service.name action: upsert value: postgresql - key: service.instance.id action: upsert value: address-of-postgres-instance:5432 service: # Telemetry for the collector itself telemetry: logs: # Sets the minimum enabled logging level # Values: debug, info, warn, error # Default = info level: info pipelines: logs/sqlquery: receivers: [ sqlquery ] processors: [ batch/sqlquery, resource ] exporters: [ otlp_http/sqlquery/logs ]Start pgpro-otel-collector with the created configuration file:
build/pgpro-otel-collector/pgpro-otel-collector --config configs/sqlquery.yml
For the full list of the sqlquery configuration parameters, refer to the OpenTelemetry documentation.
3.3.1.5. Configuring the attributes, resource, and filter Processors #
The attributes, resource, and filter processors are open-source components of the OpenTelemetry Collector.
The processor configuration also depends on the database instance setup and the log format used (see the logging_collector and log_destination parameters).
The resource processor needs to be configured when sending logs to Elastic. Regardless of the log format, the service.name and service.instance.id attributes need to be specified.
Logs can be filtered by severity level using the filter processor, as shown in the examples below.
An example of setting up processors for collecting logs in the JSON format:
processors:
filter/include:
logs:
include:
match_type: strict # Or regexp
severity_texts:
# - "DEBUG"
- "INFO"
- "NOTICE"
- "WARNING"
- "ERROR"
- "LOG"
- "FATAL"
- "PANIC"
attributes/convert:
actions:
- key: query_id
action: convert
converted_type: string
- key: pid
action: convert
converted_type: string
resource:
attributes:
- key: service.name
action: upsert
value: postgresql
- key: service.instance.id
action: upsert
value: 1.2.3.4:5432
An example of setting up processors for collecting logs in the CSV format:
processors:
filter/include:
logs:
include:
match_type: strict # Or regexp
severity_texts:
# - "DEBUG"
- "INFO"
- "NOTICE"
- "WARNING"
- "ERROR"
- "LOG"
- "FATAL"
- "PANIC"
attributes/convert:
actions:
- key: pid
action: convert
converted_type: int
- key: line_num
action: convert
converted_type: int
- key: txid
action: convert
converted_type: int
key: remote_port
action: convert
converted_type: int
- key: cursor_position
action: convert
converted_type: int
- key: internal_position
action: convert
converted_type: int
- key: leader_pid
action: convert
converted_type: int
resource:
attributes:
- key: service.name
action: upsert
value: postgresql
- key: service.instance.id
action: upsert
value: 1.2.3.4:5432
3.3.1.6. Configuring the otlp_http Exporter #
Important
otlphttp has been renamed to otlp_http to comply with the component naming convention. The deprecated alias is still supported but produces warnings and will be completely removed in future releases. Update your configuration accordingly.
The otlp_http exporter is an open-source component of the OpenTelemetry Collector and is used for exporting collected logs to an OTLP-compatible storage or monitoring system that has to be predeployed and accessible. For more details, refer to the OpenTelemetry documentation.
To configure the otlp_http exporter, it is sufficient to specify the address of the target system where data should be sent:
exporters:
otlp_http:
endpoint: https://otlp.example.org
3.3.1.7. Configuring the kafka Exporter #
The kafka exporter is an open-source component of the OpenTelemetry Collector for sending metrics and logs to Apache Kafka. For more details, refer to the OpenTelemetry documentation.
Below is the example of setting it up for sending logs.
receivers:
file_log:
include: [ /var/log/postgresql/*.json ]
start_at: end
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 30s
max_elapsed_time: 5m
operators:
- type: json_parser
parse_ints: true
timestamp:
parse_from: attributes.timestamp
layout_type: strptime
layout: '%Y-%m-%d %H:%M:%S.%L %Z'
severity:
parse_from: attributes.error_severity
mapping:
debug: [ DEBUG ]
info: [ INFO, NOTICE, LOG ]
warn: [ WARNING ]
error: [ ERROR ]
fatal: [ FATAL, PANIC ]
- type: remove
id: remove_timestamp
field: attributes.timestamp
exporters:
kafka:
brokers:
- localhost:9092
protocol_version: 2.1.0
client_id: pgpro-otel-collector
logs:
topic: otlp_logs
encoding: otlp_json # proto supported
include_metadata_keys:
- service.name
- service.instance.id
# tls:
# insecure: false
# # Required for self-signed certificates (system root CAs are used if empty)
# ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt
# # cert_file/key_file: required for mTLS
# cert_file: /etc/pgpro-otel-collector/cert.d/client.crt
# key_file: /etc/pgpro-otel-collector/cert.d/client.key
# min_version: "1.3"
timeout: 30s
producer:
max_message_bytes: 1000000
required_acks: 1
compression: none # gzip, snappy, lz4, and zstd;
processors:
batch/kafka:
send_batch_size: 1024
timeout: 1s
attributes/convert:
actions:
- key: query_id
action: convert
converted_type: string
resource:
attributes:
- key: service.name
action: upsert
value: postgresql
- key: service.instance.id
action: upsert
value: address-of-postgres-instance:5432
service:
pipelines:
logs/kafka:
receivers: [ file_log ]
processors: [ batch/kafka,resource,attributes/convert ]
exporters: [ kafka ]
For more details on TLS configuration parameters, refer to Section 3.6.4.
3.3.1.8. Setting up a Pipeline #
Once receivers, processors, and exporters are added and configured, they need to be combined into a pipeline. The pipeline is configured in the service section. The pipeline contents depend altogether on the previously added components (there is no default configuration).
Below is the example of how to set up a pipeline for log management. The data is collected by the file_log receiver, processed by the resource and attributes processors and exported by the otlp_http exporter.
Thus, all the components used in the pipeline should also be added in the configuration file and set up.
service:
extensions: []
pipelines:
logs:
receivers:
- file_log
processors:
- resource
- attributes/convert
exporters:
- otlp_http
3.3.2. Use Cases #
3.3.2.1. Using pgpro-otel-collector with VictoriaLogs #
VictoriaLogs is a log management system that can receive OpenTelemetry logs via OTLP over HTTP. Follow the procedure below to set up pgpro-otel-collector for export to VictoriaLogs.
Create the
victorialogs.ymlconfiguration file with the following content:exporters: otlp_http/victorialogs: compression: gzip # The encoding to use for messages (must be "proto", which is the default value) encoding: proto # The base URL of the VictoriaLogs endpoint to send data to (without a suffix) # By default, the collector appends /v1/logs endpoint: http://localhost:9428/insert/opentelemetry # tls: # insecure: false # # Required for self-signed certificates (system root CAs are used if empty) # ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt # # cert_file/key_file: required for mTLS # cert_file: /etc/pgpro-otel-collector/cert.d/client.crt # key_file: /etc/pgpro-otel-collector/cert.d/client.key # min_version: "1.3" processors: resource: attributes: - key: service.name action: upsert value: postgresql - key: service.instance.id action: upsert value: address-of-postgres-instance:5432 service: extensions: [] pipelines: logs: receivers: [ file_log ] processors: [ resource ] exporters: [ otlp_http/victorialogs ]gzipis the default value for thecompressionparameter. It reduces network bandwidth usage and is recommended for VictoriaLogs. For more information, refer to the OpenTelemetry documentation.VictoriaLogs infers the types of attributes based on their values. To send logs to another system, like Elasticsearch, consider using the
convertprocessor. For more details, refer to the example setup shown in thelogs_json.ymlfile.Note
VictoriaLogs uses
_streamfields for efficient log organization and querying. Theresourceprocessor defines these streams. Only include attributes that are frequently used in queries. For more information about streams, refer to the VictoriaLogs documentation.Start pgpro-otel-collector with the created
victorialogs.ymlconfiguration file and the preferred log configuration:build/pgpro-otel-collector/pgpro-otel-collector --config configs/logs_json.yml --config configs/victorialogs.yml # Or build/pgpro-otel-collector/pgpro-otel-collector --config configs/logs_csv.yml --config configs/victorialogs.yml
Verify that logs are visible in the UI:
http://localhost:9428/select/vmui
For detailed information on OpenTelemetry integration with VictoriaLogs, refer to the VictoriaMetrics documentation.
3.3.2.2. Collecting CSV Logs from pg_proaudit #
pg_proaudit is a Postgres Pro Enterprise extension that enables detailed logging of various security events. This section explains how to configure pgpro-otel-collector to read audit events from CSV log files and export them to Elasticsearch and VictoriaLogs.
3.3.2.2.1. Prerequisites #
To collect CSV logs from pg_proaudit, the following requirements must be met:
The pg_proaudit extension must be installed and enabled.
The
pg_proaudit.log_destinationparameter must includecsvlog.The
includepath must point to the actual log files, as defined bypg_proaudit.log_directoryandpg_proaudit.log_filename.
3.3.2.2.2. Configuration Procedure #
Create a configuration file, for example
pg_proaudit_csv.yml.In the
receiverssection of the created file, configure afile_logreceiver:receivers: file_log: include: [ /var/lib/postgresql/data/pg_proaudit/*.log ] start_at: end retry_on_failure: enabled: true initial_interval: 1s max_interval: 30s max_elapsed_time: 5m multiline: line_start_pattern: ^[0-9]{4}-[0-9]{2}-[0-9]{2} operators: - type: csv_parser header: log_time,current_username,database_name,pid,severity,command_line_num,subcommand_line_num,operator_name,object_type,object_name,result,info,query_text,query_params,session_username,uuid,txid,vxid,rows timestamp: parse_from: attributes.log_time layout_type: strptime layout: '%Y-%m-%d %H:%M:%S.%L %Z' severity: parse_from: attributes.severity mapping: info: [ INFO ] error: [ ERROR ] - type: remove id: remove_log_time field: attributes.log_time - type: remove id: remove_severity field: attributes.severityWhere:
includemust contain the path that matches thepg_proaudit.log_directoryandpg_proaudit.log_filenameparameter values. Default:pg_proaudit/postgresql-%Y-%m-%d_%H%M%S.log.operators.headerspecifies a comma-separated list of pg_proaudit CSV fields in the order they appear in the log file.
For more details on the
file_logreceiver configuration, refer to Section 3.3.1.1.Configure the
attributesprocessor to convert numeric fields to proper types for Elasticsearch.VictoriaLogs infers types automatically, so it does not require this processor.
processors: attributes/convert: actions: - key: pid action: convert converted_type: string - key: txid action: convert converted_type: int - key: rows action: convert converted_type: int - key: command_line_num action: convert converted_type: int - key: subcommand_line_num action: convert converted_type: intConfigure the
resourceprocessor to define log streams in VictoriaLogs and index metadata in Elasticsearch:resource: attributes: - key: service.name action: upsert value: pg_proaudit - key: service.instance.id action: upsert value: address-of-postgres-instance:5432Configure the
otlp_httpexporters — one for each destination:exporters: otlp_http/elasticsearch: endpoint: https://ppem-es-apm.example.org tls: insecure_skip_verify: false compression: "" otlp_http/victorialogs: endpoint: http://localhost:9428/insert/opentelemetry compression: gzip encoding: proto tls: insecure_skip_verify: falseLogs are exported to Elasticsearch through Elastic APM Server, which must be configured to accept OTLP logs. For details, refer to the Elastic documentation.
For more information on OTLP HTTP log export to VictoriaLogs, refer to the VictoriaLogs documentation.
Configure the service pipelines:
service: extensions: [] pipelines: logs/elasticsearch: receivers: [ file_log ] processors: [ attributes/convert, resource ] exporters: [ otlp_http/elasticsearch ] logs/victorialogs: receivers: [ file_log ] processors: [ resource ] exporters: [ otlp_http/victorialogs ]To send logs to only one destination, simply remove the unwanted pipeline from the
servicesection.Start pgpro-otel-collector with the created configuration file:
pgpro-otel-collector --config configs/pg_proaudit_csv.yml