Course contentsShow
← Databases & SQL
Lesson 957 of 1,9538. PostgreSQL InternalsFree lesson

Audit Logging with pgaudit

You will install and configure pgaudit to generate comprehensive session and object audit trails.

In this lesson, you will learn how to implement robust, granular audit trails in PostgreSQL using the pgaudit extension to track database activity beyond standard server logs.

Why pgaudit?

Standard PostgreSQL logging (log_statement = 'all') is often insufficient for compliance and security auditing. It mixes application traffic with system events and lacks the structural clarity required to easily parse who did what to specific sensitive objects. pgaudit (PostgreSQL Audit Extension) provides detailed session and object-level auditing, capturing the exact DDL and DML operations performed.

Installation and Configuration

First, ensure the extension is available on your system, then enable it in your postgresql.conf file:

# Load the extension at startup
shared_preload_libraries = 'pgaudit'

# Set the audit log destination
pgaudit.log = 'read, write, ddl'

Once configured and the server is restarted, you can initialize the extension in your database: CREATE EXTENSION pgaudit;

Session vs. Object Auditing

pgaudit operates in two primary modes:

  1. Session Auditing: Logs all statements executed by a user or role. This is useful for monitoring privileged accounts.
  2. Object Auditing: Logs specific operations on specific tables. You can apply this by granting the pgaudit.role to a user and creating a security policy on an object.

For example, to audit all updates on a sensitive_payroll table, you would link the audit role to that object. When an update occurs, pgaudit creates an entry in the log that explicitly separates the command type, the object accessed, and the user identity, making it far easier to filter through pg_log entries later using tools like grep or log aggregators.

By utilizing pgaudit, you move away from messy, unstructured text logs and toward a structured, reliable audit trail that satisfies regulatory requirements and internal security governance.

Key Takeaway: Use pgaudit to generate structured, object-aware audit trails that provide the high-fidelity visibility needed for secure database operations.