Creating a trigger-based audit log for PostgreSQL
Latest commit 75be579 Mar 9, 2016 Suman Gurung v0.6.6
Failed to load latest commit information.
lib v0.6.6 Mar 9, 2016
spec RSpec 3 May 23, 2015
.gitignore Update gitignore May 23, 2015
.rspec Lock to rspec 2.14.1 until syntax can be updated Oct 24, 2014
.travis.yml v0.6.6 Mar 9, 2016
Gemfile Fix incorrect ENV variable names for test suite version changing Oct 28, 2014
LICENSE It's 2014 May 16, 2014 Use SVG build status badge May 23, 2015
Rakefile More modern Rakefile May 16, 2014
pg_audit_log.gemspec RSpec 3 May 23, 2015


Build Status Code Climate Gem Version


PostgreSQL-only database-level audit logging of all databases changes using a completely transparent stored procedure and triggers. Comes with specs for your project and a rake task to generate the reverse SQL to undo changes logged.

All SQL INSERTs, UPDATEs, and DELETEs will be captured. Record columns that do not change do not generate an audit log entry.


  • First, enable plpgsql langauges in your postgresql instance. Execute the following as a superuser in postgres make sure your database has plpgsql enabled:

  • Generate the appropriate Rails files:

    rails generate pg_audit_log:install
  • Install the PostgreSQL function and triggers for your project:

    rake pg_audit_log:install


The PgAuditLog::Entry ActiveRecord model represents a single entry in the audit log table. Each entry represents a single change to a single field of a record in a table. So if you change 3 columns of a record, that will generate 3 corresponding PgAuditLog::Entry records.

You can see the SQL it injects on every query by running with LOG_AUDIT_SQL



schema.rb and development_structure.sql

Since schema.rb cannot represent TRIGGERs or FUNCTIONs you will need to set your environment to generate SQL instead of Ruby for your database schema and structure. In your application environment put the following:

config.active_record.schema_format = :sql

And you can generate this sql using:

rake db:structure:dump


rake pg_audit_log:uninstall


On a 2.93GHz i7 with PostgreSQL 9.1 the audit log has an overhead of about 0.0035 seconds to each INSERT, UPDATE, or DELETE.


  • ActiveRecord
  • PostgreSQL
  • Rails 3.2, 4.x


Copyright © 2010–2014 Case Commons, LLC. Licensed under the MIT license, available in the “LICENSE” file.