pgAudit

Also known as: PostgreSQL Audit Extension

On this page 7

pgAudit, the PostgreSQL Audit Extension, is an open-source extension that produces detailed, structured audit records of SQL statements executed in a PostgreSQL database and writes them to the standard server log. In database security, it fills the gap between the general statement logging built into PostgreSQL and the evidence-grade audit trail that regulators, auditors and incident responders expect from systems that hold sensitive data.

Where the core parameter log_statement records only the text a client sent, pgAudit records what the server actually executed, classified by statement type and, optionally, by the specific tables and columns touched. This makes it a standard building block for compliance with frameworks such as PCI DSS, HIPAA, SOX and ISO/IEC 27001 in organizations that run PostgreSQL.

How pgAudit captures SQL activity

pgAudit works by hooking into the PostgreSQL executor and utility hooks, the internal points where the server runs parsed and planned statements. Because it observes statements after parsing, it sees the fully resolved object names, including statements generated inside functions, DO blocks and dynamic SQL that log_statement would never reveal.

The extension must be loaded at server start through shared_preload_libraries = 'pgaudit', after which a server restart is required and CREATE EXTENSION pgaudit is run in each database where its functions are needed. Each audit entry is emitted through the normal logging subsystem with the prefix AUDIT:, so it travels wherever the server log goes, whether to files, syslog or the Windows event log.

A single audit line contains several comma-separated fields that make records machine-parseable. The following table describes those fields and why each one matters during an investigation.

FieldContentInvestigative value
Audit typeSESSION or OBJECTShows which logging mode produced the record
Statement IDSequential number per sessionLinks all parts of one statement
Substatement IDNumber within a statementReveals nested calls inside functions
ClassREAD, WRITE, DDL, ROLE and othersSupports filtering by activity category
CommandSELECT, ALTER TABLE, GRANTIdentifies the exact operation
Object type and nameTABLE public.paymentsPinpoints the affected object
Statement and parametersFull SQL text, optional bind valuesReconstructs what was executed
Fields in a pgAudit log entry

Session audit logging and object audit logging

pgAudit offers two complementary logging modes that answer different audit questions. Session audit logging records every statement of selected classes executed by a user session, while object audit logging records only statements that touch specific relations, with far less noise.

Session logging is controlled by the parameter pgaudit.log, which accepts a list of statement classes. Object logging uses a dedicated audit role named in pgaudit.role: privileges granted to that role on a table or column define what is audited, so granting SELECT on payments.card_number to the audit role causes every read of that column to be logged.

ClassStatements coveredTypical audit purpose
READSELECT, COPY from a relationDetect access to sensitive data
WRITEINSERT, UPDATE, DELETE, TRUNCATE, COPY to a relationTrack data changes
DDLCREATE, ALTER, DROP outside the ROLE classControl schema changes
ROLEGRANT, REVOKE, CREATE ROLE, ALTER ROLEMonitor privilege changes
FUNCTIONFunction calls and DO blocksReveal code-driven activity
MISCDISCARD, FETCH, CHECKPOINT, VACUUM, SETRecord administrative commands
MISC_SETSET ROLE and other SET commandsDetect identity switching
Statement classes available in pgaudit.log

A common production pattern combines session logging of DDL and ROLE for all users with object logging of reads on a short list of regulated tables. This captures every structural and privilege change while keeping data access records focused on the columns that auditors actually examine.

pgAudit is not a replacement for all logging; it is one layer among several options that differ in granularity and overhead. The comparison below places it next to the mechanisms most often confused with it.

MechanismWhat it recordsMain limitation
log_statementClient-submitted SQL textMisses SQL inside functions and dynamic code
log_connections and log_disconnectionsSession start and endNo information about statements
pgAuditClassified executed statements and objectsLog volume grows quickly with READ auditing
Trigger-based audit tablesRow values before and after changesCannot capture reads, adds write latency
Database activity monitoringNetwork or agent view across platformsSeparate product, extra infrastructure
pgAudit and neighboring logging mechanisms

In the vocabulary of database security, pgAudit implements a database audit function natively inside PostgreSQL. It records evidence but does not block queries, which distinguishes it from a database firewall, and it does not decide who may see rows, which remains the task of row-level security and privileges.

Configuring pgAudit for production

Effective configuration starts from the audit requirement, not from enabling every class. Auditing everything with pgaudit.log = 'all' on a busy system can generate gigabytes of log data per hour and measurable CPU overhead, so most teams scope logging deliberately.

Settings can be applied at several levels: globally in postgresql.conf, per database with ALTER DATABASE, or per role with ALTER ROLE, which allows strict logging for administrators and application service accounts without flooding the log with routine reporting queries.

Audit goalRecommended settingReason
Track privilege changespgaudit.log = ‘role, ddl’Low volume, high audit value
Prove access to card dataObject logging via pgaudit.roleLimits records to regulated columns
Monitor superusersALTER ROLE admin SET pgaudit.log = ‘all’Full trail for the most powerful accounts
Reconstruct exact queriespgaudit.log_parameter = onCaptures bind values used at runtime
Reduce duplicate entriespgaudit.log_statement_once = onWrites statement text only once per statement
Exclude catalog noisepgaudit.log_catalog = offSkips queries against system catalogs
Configuration choices by audit goal

Audit records are only useful if they are protected and retained. Logs should be shipped promptly to a separate log platform or SIEM where database administrators cannot alter them, because an attacker with superuser rights can also change logging settings or remove local log files.

Limitations, risks and common mistakes

pgAudit is powerful but has well-known blind spots that experienced practitioners plan around. The most important one is that a superuser can disable auditing for a session with SET pgaudit.log = 'none', although that change itself is recorded when the MISC_SET class is enabled.

  • Logging bind parameters can write personal data or secrets into logs, which then require the same protection as the database itself.
  • Failed statements that never reach the executor, such as syntax errors, are not audited by pgAudit and appear only in standard error logging.
  • Object logging depends on privileges, so a table missing from the audit role grants silently goes unaudited.
  • Version alignment matters: each pgAudit release line targets a specific PostgreSQL major version, and upgrades must include a matching build.
  • Log rotation without retention policy can delete evidence before an incident is detected.

Managed services such as Amazon RDS, Azure Database for PostgreSQL and Google Cloud SQL generally support pgAudit through parameter groups or database flags, but they may restrict certain settings, so the available configuration should be verified for each platform.

The idea in brief

pgAudit is like a security camera inside a PostgreSQL database. Ordinary logging notes roughly what people asked for, but pgAudit writes down exactly what the database did, who did it and which tables were involved.

Teams choose what the camera watches. They can record every change to user permissions, or only reads of a few sensitive tables, such as those holding payment or health data. The key point is simple: pgAudit creates evidence, so when an auditor or investigator asks who looked at certain data, there is a reliable answer.

A practical scenario

An online retailer stores payment tokens in a PostgreSQL 16 database and must demonstrate PCI DSS compliance. The database team loads pgAudit, sets pgaudit.log = 'ddl, role' globally and creates an audit role that holds SELECT and UPDATE grants on the payments table, which turns on object logging for that table only.

All audit lines are forwarded through syslog to a central SIEM within seconds. Months later, an internal review flags an unusual export. Investigators filter the SIEM for AUDIT: OBJECT entries on public.payments and find that a reporting account ran a broad SELECT from inside a scheduled function, something plain log_statement would have missed.

The team revokes the account’s access, adds the incident to its records and shows the auditor the complete trail. The investigation took hours rather than weeks, and the retailer passed its assessment with the audit configuration documented as a compensating control.