TigerData logo
TigerData logo
  • Product

    Tiger Cloud

    Robust elastic cloud platform for startups and enterprises

    Agentic Postgres

    Postgres for Agents

    TimescaleDB

    Postgres for time-series, real-time analytics and events

  • Docs
  • Pricing

    Pricing

    Enterprise Tier

  • Developer Hub

    Changelog

    Benchmarks

    Blog

    Community

    Customer Stories

    Events

    Support

    Integrations

    Launch Hub

  • Company

    Contact us

    About

    Timescale

    Partners

    Security

    Careers

Log InTry for free
Home
AWS Time-Series Database: Understanding Your OptionsStationary Time-Series AnalysisThe Best Time-Series Databases ComparedTime-Series Analysis and Forecasting With Python Alternatives to TimescaleWhat Are Open-Source Time-Series Databases—Understanding Your OptionsWhy Consider Using PostgreSQL for Time-Series Data?Time-Series Analysis in RWhat Is Temporal Data?What Is a Time Series and How Is It Used?Is Your Data Time Series? Data Types Supported by PostgreSQL and TimescaleUnderstanding Database Workloads: Variable, Bursty, and Uniform PatternsHow to Work With Time Series in Python?Tools for Working With Time-Series Analysis in PythonGuide to Time-Series Analysis in PythonUnderstanding Autoregressive Time-Series ModelingCreating a Fast Time-Series Graph With Postgres Materialized Views
Understanding PostgreSQLOptimizing Your Database: A Deep Dive into PostgreSQL Data TypesUnderstanding FROM in PostgreSQL (With Examples)How to Address ‘Error: Could Not Resize Shared Memory Segment’ How to Install PostgreSQL on MacOSUnderstanding FILTER in PostgreSQL (With Examples)Understanding GROUP BY in PostgreSQL (With Examples)PostgreSQL Join Type TheoryA Guide to PostgreSQL ViewsStructured vs. Semi-Structured vs. Unstructured Data in PostgreSQLUnderstanding Foreign Keys in PostgreSQLUnderstanding PostgreSQL User-Defined FunctionsUnderstanding PostgreSQL's COALESCE FunctionUnderstanding SQL Aggregate FunctionsUsing PostgreSQL UPDATE With JOINHow to Install PostgreSQL on Linux5 Common Connection Errors in PostgreSQL and How to Solve ThemUnderstanding HAVING in PostgreSQL (With Examples)How to Fix No Partition of Relation Found for Row in Postgres DatabasesHow to Fix Transaction ID Wraparound ExhaustionUnderstanding LIMIT in PostgreSQL (With Examples)Understanding PostgreSQL FunctionsUnderstanding ORDER BY in PostgreSQL (With Examples)Understanding WINDOW in PostgreSQL (With Examples)Understanding PostgreSQL WITHIN GROUPPostgreSQL Mathematical Functions: Enhancing Coding EfficiencyUnderstanding DISTINCT in PostgreSQL (With Examples)Using PostgreSQL String Functions for Improved Data AnalysisData Processing With PostgreSQL Window FunctionsPostgreSQL Joins : A SummaryUnderstanding OFFSET in PostgreSQL (With Examples)Understanding PostgreSQL Date and Time FunctionsWhat Is Data Compression and How Does It Work?What Is Data Transformation, and Why Is It Important?Understanding the Postgres string_agg FunctionWhat Is a PostgreSQL Left Join? And a Right Join?Understanding PostgreSQL SELECTSelf-Hosted or Cloud Database? A Countryside Reflection on Infrastructure ChoicesUnderstanding ACID Compliance Understanding percentile_cont() and percentile_disc() in PostgreSQLUnderstanding PostgreSQL Conditional FunctionsUnderstanding PostgreSQL Array FunctionsWhat Characters Are Allowed in PostgreSQL Strings?Understanding WHERE in PostgreSQL (With Examples)What Is a PostgreSQL Full Outer Join?What Is a PostgreSQL Cross Join?What Is a PostgreSQL Inner Join?Data Partitioning: What It Is and Why It MattersStrategies for Improving Postgres JOIN PerformanceUnderstanding the Postgres extract() FunctionUnderstanding the rank() and dense_rank() Functions in PostgreSQL
Guide to PostgreSQL PerformanceHow to Reduce Bloat in Large PostgreSQL TablesDesigning Your Database Schema: Wide vs. Narrow Postgres TablesBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables Best Practices for (Time-)Series Metadata Tables A Guide to Data Analysis on PostgreSQLA Guide to Scaling PostgreSQLGuide to PostgreSQL SecurityHandling Large Objects in PostgresHow to Query JSON Metadata in PostgreSQLHow to Query JSONB in PostgreSQLHow to Use PostgreSQL for Data TransformationOptimizing Array Queries With GIN Indexes in PostgreSQLPg_partman vs. Hypertables for Postgres PartitioningPostgreSQL Performance Tuning: Designing and Implementing Your Database SchemaPostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesDetermining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)Top PostgreSQL Drivers for PythonWhen to Consider Postgres PartitioningGuide to PostgreSQL Database OperationsUnderstanding PostgreSQL TablespacesWhat Is Audit Logging and How to Enable It in PostgreSQLGuide to Postgres Data ManagementHow to Index JSONB Columns in PostgreSQLHow to Monitor and Optimize PostgreSQL Index PerformanceSQL/JSON Data Model and JSON in SQL: A PostgreSQL PerspectiveA Guide to pg_restore (and pg_restore Example)PostgreSQL Performance Tuning: How to Size Your DatabaseAn Intro to Data Modeling on PostgreSQLExplaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?A PostgreSQL Database Replication GuideHow to Compute Standard Deviation With PostgreSQLHow PostgreSQL Data Aggregation WorksBuilding a Scalable DatabaseRecursive Query in SQL: What It Is, and How to Write OneGuide to PostgreSQL Database DesignHow to Use Psycopg2: The PostgreSQL Adapter for Python
Best Practices for Scaling PostgreSQLHow to Design Your PostgreSQL Database: Two Schema ExamplesHow to Handle High-Cardinality Data in PostgreSQLHow to Store Video in PostgreSQL Using BYTEABest Practices for PostgreSQL Database OperationsHow to Manage Your Data With Data Retention PoliciesBest Practices for PostgreSQL AggregationBest Practices for Postgres Database ReplicationHow to Use a Common Table Expression (CTE) in SQLBest Practices for Postgres Data ManagementBest Practices for Postgres PerformanceBest Practices for Postgres SecurityBest Practices for PostgreSQL Data AnalysisTesting Postgres Ingest: INSERT vs. Batch INSERT vs. COPYHow to Use PostgreSQL for Data Normalization
PostgreSQL Extensions: amcheckPostgreSQL Extensions: Unlocking Multidimensional Points With Cube PostgreSQL Extensions: hstorePostgreSQL Extensions: ltreePostgreSQL Extensions: Secure Your Time-Series Data With pgcryptoPostgreSQL Extensions: pg_prewarmPostgreSQL Extensions: pgRoutingPostgreSQL Extensions: pg_stat_statementsPostgreSQL Extensions: Install pg_trgm for Data MatchingPostgreSQL Extensions: Turning PostgreSQL Into a Vector Database With pgvectorPostgreSQL Extensions: Database Testing With pgTAPPostgreSQL Extensions: PL/pgSQLPostgreSQL Extensions: Using PostGIS and Timescale for Advanced Geospatial InsightsPostgreSQL Extensions: Intro to uuid-ossp
Columnar Databases vs. Row-Oriented Databases: Which to Choose?Data Analytics vs. Real-Time Analytics: How to Pick Your Database (and Why It Should Be PostgreSQL)How to Choose a Real-Time Analytics DatabaseUnderstanding OLTPOLAP Workloads on PostgreSQL: A GuideHow to Choose an OLAP DatabasePostgreSQL as a Real-Time Analytics DatabaseWhat Is the Best Database for Real-Time AnalyticsHow to Build an IoT Pipeline for Real-Time Analytics in PostgreSQL
When Should You Use Full-Text Search vs. Vector Search?HNSW vs. DiskANNA Brief History of AI: How Did We Get Here, and What's Next?A Beginner’s Guide to Vector EmbeddingsPostgreSQL as a Vector Database: A Pgvector TutorialUsing Pgvector With PythonHow to Choose a Vector DatabaseVector Databases Are the Wrong AbstractionUnderstanding DiskANNA Guide to Cosine SimilarityStreaming DiskANN: How We Made PostgreSQL as Fast as Pinecone for Vector DataImplementing Cosine Similarity in PythonVector Database Basics: HNSWVector Database Options for AWSVector Store vs. Vector Database: Understanding the ConnectionPgvector vs. Pinecone: Vector Database Performance and Cost ComparisonHow to Build LLM Applications With Pgvector Vector Store in LangChainHow to Implement RAG With Amazon Bedrock and LangChainRetrieval-Augmented Generation With Claude Sonnet 3.5 and PgvectorRAG Is More Than Just Vector SearchPostgreSQL Hybrid Search Using Pgvector and CohereImplementing Filtered Semantic Search Using Pgvector and JavaScriptRefining Vector Search Queries With Time Filters in Pgvector: A TutorialUnderstanding Semantic SearchWhat Is Vector Search? Vector Search vs Semantic SearchText-to-SQL: A Developer’s Zero-to-Hero GuideNearest Neighbor Indexes: What Are IVFFlat Indexes in Pgvector and How Do They WorkBuilding an AI Image Gallery With OpenAI CLIP, Claude Sonnet 3.5, and Pgvector
Understanding IoT (Internet of Things)A Beginner’s Guide to IIoT and Industry 4.0Storing IoT Data: 8 Reasons Why You Should Use PostgreSQLMoving Past Legacy Systems: Data Historian vs. Time-Series DatabaseWhy You Should Use PostgreSQL for Industrial IoT DataHow to Choose an IoT DatabaseHow to Simulate a Basic IoT Sensor Dataset on PostgreSQLFrom Ingest to Insights in Milliseconds: Everactive's Tech Transformation With TimescaleHow Ndustrial Is Providing Fast Real-Time Queries and Safely Storing Client Data With 97 % CompressionHow Hopthru Powers Real-Time Transit Analytics From a 1 TB Table Migrating a Low-Code IoT Platform Storing 20M Records/DayHow United Manufacturing Hub Is Introducing Open Source to ManufacturingBuilding IoT Pipelines for Faster Analytics With IoT CoreVisualizing IoT Data at Scale With Hopara and TimescaleDB
What Is ClickHouse and How Does It Compare to PostgreSQL and TimescaleDB for Time Series?Timescale vs. Amazon RDS PostgreSQL: Up to 350x Faster Queries, 44 % Faster Ingest, 95 % Storage Savings for Time-Series DataWhat We Learned From Benchmarking Amazon Aurora PostgreSQL ServerlessTimescaleDB vs. Amazon Timestream: 6,000x Higher Inserts, 5-175x Faster Queries, 150-220x CheaperHow to Store Time-Series Data in MongoDB and Why That’s a Bad IdeaPostgreSQL + TimescaleDB: 1,000x Faster Queries, 90 % Data Compression, and Much MoreEye or the Tiger: Benchmarking Cassandra vs. TimescaleDB for Time-Series Data
Alternatives to RDSWhy Is RDS so Expensive? Understanding RDS Pricing and CostsEstimating RDS CostsHow to Migrate From AWS RDS for PostgreSQL to TimescaleAmazon Aurora vs. RDS: Understanding the Difference
5 InfluxDB Alternatives for Your Time-Series Data8 Reasons to Choose Timescale as Your InfluxDB Alternative InfluxQL, Flux, and SQL: Which Query Language Is Best? (With Cheatsheet)What InfluxDB Got WrongTimescaleDB vs. InfluxDB: Purpose Built Differently for Time-Series Data
5 Ways to Monitor Your PostgreSQL DatabaseHow to Migrate Your Data to Timescale (3 Ways)Postgres TOAST vs. Timescale CompressionBuilding Python Apps With PostgreSQL: A Developer's GuideData Visualization in PostgreSQL With Apache SupersetMore Time-Series Data Analysis, Fewer Lines of Code: Meet HyperfunctionsIs Postgres Partitioning Really That Hard? An Introduction To HypertablesPostgreSQL Materialized Views and Where to Find ThemTimescale Tips: Testing Your Chunk Size
Postgres cheat sheet
HomeTime series basicsPostgres basicsPostgres guidesPostgres best practicesPostgres extensionsPostgres for real-time analytics
Sections

Performance

Guide to PostgreSQL Performance

Schema design

PostgreSQL Performance Tuning: Designing and Implementing Your Database Schema

Performance tuning

PostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesHow to Reduce Bloat in Large PostgreSQL TablesPostgreSQL Performance Tuning: How to Size Your Database

Partitioning

Determining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)When to Consider Postgres PartitioningPg_partman vs. Hypertables for Postgres Partitioning

Database design and modeling

An Intro to Data Modeling on PostgreSQLDesigning Your Database Schema: Wide vs. Narrow Postgres TablesBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables Best Practices for (Time-)Series Metadata Tables Guide to PostgreSQL Database Design

Database replication

A PostgreSQL Database Replication Guide

Data analysis

A Guide to Data Analysis on PostgreSQLHow to Compute Standard Deviation With PostgreSQL

Data transformation

How to Use PostgreSQL for Data Transformation

Data aggregation

How PostgreSQL Data Aggregation Works

Scaling postgres

A Guide to Scaling PostgreSQLBuilding a Scalable Database

Database security

Guide to PostgreSQL SecurityWhat Is Audit Logging and How to Enable It in PostgreSQL

Data management

Understanding PostgreSQL TablespacesGuide to Postgres Data ManagementHandling Large Objects in Postgres

Database operations

Guide to PostgreSQL Database Operations

JSON

How to Query JSON Metadata in PostgreSQLHow to Query JSONB in PostgreSQLHow to Index JSONB Columns in PostgreSQLSQL/JSON Data Model and JSON in SQL: A PostgreSQL Perspective

Query optimization

Explaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?Optimizing Array Queries With GIN Indexes in PostgreSQLRecursive Query in SQL: What It Is, and How to Write One

Database tools and libraries

How to Use Psycopg2: The PostgreSQL Adapter for PythonTop PostgreSQL Drivers for Python

Database indexes

How to Monitor and Optimize PostgreSQL Index Performance

Database backups and restore

A Guide to pg_restore (and pg_restore Example)

Products

Time Series and Analytics AI and Vector Enterprise Plan Cloud Status Support Security Cloud Terms of Service

Learn

Documentation Blog Forum Tutorials Changelog Success Stories Time Series Database

Company

Contact Us Careers About Brand Community Code Of Conduct Events

Subscribe to the Tiger Data Newsletter

By submitting, you acknowledge Tiger Data's Privacy Policy

2025 (c) Timescale, Inc., d/b/a Tiger Data. All rights reserved.

Privacy preferences
LegalPrivacySitemap

Published at Jul 10, 2024

What Is Audit Logging and How to Enable It in PostgreSQL

Try for free

Start supercharging your PostgreSQL today.

A detective elephant looking through a magnifying glass to inspect those audit logs.

Written by Ana Tavares, Sarah Conway, and Doug Ortiz

Every developer working with customer data—especially sensitive data—knows that maintaining stringent security and compliance standards is critical. Among various measures, database audit logging plays a vital role in adding an extra layer of security. 

Audit logging, also known as auditing or audit trail logging, is the process of recording a detailed log of all activities and transactions performed within a system or application, particularly focusing on access and changes to data. In the context of databases, it involves tracking and documenting every action that occurs. 

If you’re a PostgreSQL user, one of the most effective ways to do audit logging is using pgAudit. This open-source extension for PostgreSQL enables detailed logging of database operations. In this blog post, we’ll explain why audit logging is crucial and how to do it in PostgreSQL using pgAudit. 

The pgAudit extension is now available to all Timescale Cloud customers directly within the Timescale console, providing detailed database session and/or object audit logging in the Timescale logs. Otherwise, we’ll walk you through installing pgAudit on your local installation later on in this article. Keep reading for more information!

What Is the Difference Between Audit Logging and an Activity Log?

The terms "audit log" and "activity log" are often used interchangeably, but they have distinct differences in terms of their focus, purpose, and content.

Audit logs are primarily used to ensure security, maintain compliance with regulations, and provide a verifiable record of actions. They are designed to track who did what, when, and how in detail. They also ensure that every action taken by users or administrators is recorded, providing a trail that can be audited to hold individuals accountable.

On the other hand, activity logs are used to monitor a system's normal operations, tracking user activities and system events to understand system health, behavior, and performance. They additionally provide insights into how users interact with the system, which can help improve user experience and optimize system performance.

What about database audit logging?

Database audit logging involves recording the actions performed on the database. Many organizations operate under strict security policies that mandate logging all operations at the database level. In PostgreSQL (and TimescaleDB), this includes but is not limited to, SQL queries, data modifications, and login attempts. Database audit logging helps monitor user activities, detect suspicious actions, and ensure compliance with regulations such as GDPR, HIPAA, and others. 

If you’re a PostgreSQL (or TimescaleDB) user, the open-source extension pgAudit helps fulfill these requirements by providing a detailed audit trail of database activities. This is particularly crucial for industries subject to rigid regulatory standards, such as healthcare, finance, and government sectors.

This is exactly the case here at Timescale, where we now provide pgAudit support to serve cloud customers who have stricter security and compliance requirements, such as the need to log all operations done at the database level. As an example, integrating pgAudit directly into our UI is a significant step for us toward delivering HIPAA support because the extension’s detailed logging capabilities ensure that all database interactions are recorded. This provides the necessary audit trails required for HIPAA compliance.

Key Components of Audit Logging

To provide a chronological record of events that can be used for security monitoring, compliance, troubleshooting, and performance analysis, audit logging includes the following key components:

  1. Event capture: Audit logs capture specific events, such as user logins, logouts, SQL queries, data changes, and modifications to the database schema.

  2. Timestamping: Each logged event is associated with a precise timestamp, indicating when the event occurred.

  3. User identification: Logs include information about the user who performed the action, providing accountability and traceability.

  4. Action details: The logs detail the nature of the action. This includes the type of operation (e.g., SELECT, INSERT, UPDATE, DELETE), the affected data or objects, and the outcome of the action.

  5. Contextual information: Additional context, such as the source IP address, application name, and session ID, may be recorded to provide a comprehensive understanding of the event.

In short, these are the components that will be kept in your PostgreSQL audit table. Now, let’s see how you can create it using pgAudit.

PgAudit: The PostgreSQL Audit Extension

PgAudit is a PostgreSQL extension that allows administrators to audit database activities at both the session and object levels. Since our goal is to save developers’ time, we’ll first show you how to easily enable it in Timescale Cloud (you can create a free account and take it for a spin for 30 days to try our automated data partitioning, hybrid row-columnar storage, incremental up-to-date materializations, and advanced data compression techniques).

If you don’t mind the added work, we’ll then show you how to configure it in vanilla PostgreSQL or self-hosted TimescaleDB.

How to enable and configure pgAudit in Timescale Cloud

Enabling and configuring pgAudit in your Timescale database is straightforward. The default configuration parameters require superuser access and can be set through the Timescale service interface. Follow these steps to configure pgAudit:

Step 1: Access database parameters 

Click on the Services link on the left-hand navigation.

image

Click on the service you wish to configure.

image

Navigate to the Service information section in your Timescale interface.

image

Click on the Operations tab, followed by the Database Parameters link on the left-hand Operations navigation, and finally, the Advanced Parameters tab on the Database parameters section.

imageimageimage

Step 2: Configure pgAudit

Search for the ‘pgaudit’ extension in the Database parameters list.

Add the values you want to set in the ‘pgaudit.log’ and ‘pgaudit.log_client' common parameters.

image

For detailed instructions and configuration options, check the pgAudit documentation.

To maximize the utility of your audit logs, you can export them to CloudWatch. This allows you to retain the logs for extended periods and leverage CloudWatch's monitoring and alerting capabilities. This blog post will guide you on integrating Amazon CloudWatch with your Timescale service.

How to enable pgAudit in PostgreSQL on Linux

In this section, we’ll cover:

  • Installing pgaudit

  • Setting up your environment

  • Configuring pgaudit for the first time

Step 1: Install PostgreSQL and development tools

First, ensure you have PostgreSQL and the necessary development tools installed on your system.

For Ubuntu/Debian:

sudo apt-get update sudo apt-get install postgresql postgresql-contrib postgresql-server-dev-all

For CentOS/RHEL:

sudo yum install postgresql-server postgresql-contrib postgresql-devel Afterward, verify your PostgreSQL installation by checking the current psql version.

psql -V You should see a result similar to the following:

psql (PostgreSQL) 16.3 (Ubuntu 16.3-0ubuntu0.24.04.1)

Step 2: Install pgaudit

The pgaudit extension might be available through your package manager. Alternatively, you can compile it from source.

Installing via Package Manager

For Ubuntu/Debian:

sudo apt-get install postgresql-XX-pgaudit  # replace XX with your PostgreSQL version

For CentOS/RHEL:

sudo yum install pgaudit

Step 3: Configure PostgreSQL

1. Edit postgresql.conf: Locate the postgresql.conf file, usually found in the PostgreSQL data directory. 

As the root user, add or modify the following configuration settings:

shared_preload_libraries = 'pgaudit'

Optionally, you can add more pgaudit configurations like:

pgaudit.log = 'all, -misc'

More configurations can be found within the official pgAudit documentation.

2. Restart PostgreSQL: Restart the PostgreSQL service to apply the changes.

sudo systemctl restart postgresql

Step 4: Create the extension in the database

1. Connect to your PostgreSQL instance:

   sudo -su postgres    psql

2. Create the extension in the desired database:    CREATE EXTENSION pgaudit;    

Step 5: Verify installation

To verify that pgaudit is installed and configured correctly, you can run the following query:

SELECT * FROM pg_extension WHERE extname = 'pgaudit';

Or alternatively, use the shortcut:

\dx pgaudit

You should see an entry for pgaudit.

Additional Configuration (Optional): Logging different activities

You can configure pgaudit to log different types of activities. For example:

ALTER SYSTEM SET pgaudit.log = 'read, write';

After making changes to postgresql.conf or using ALTER SYSTEM, always remember to reload or restart PostgreSQL as your system user. sudo systemctl reload postgresql

Example use case: Logging SELECT statements

Here's an example of how you might use pgaudit to log SELECT statements on a specific table:

1. Enable auditing for a specific table:

CREATE TABLE example_table (id serial PRIMARY KEY, data text);

2. Run a SELECT statement:

SELECT * FROM example_table;

For Timescale Cloud

Check your PostgreSQL logs to see the auditing information recorded by pgaudit. In Timescale Cloud, it’s as easy as navigating to the Logs tab within your service.

Once you have selected the Timescale service you want to inspect the logs, click the Logs tab for the service.

image

And here are your logs.

image

For a local installation (PostgreSQL or self-hosted TimescaleDB)

You can locate your log directory using the following:

SHOW log_directory;

If it’s a relative path, it’ll be relative to the root path for the data directory that you identified earlier.

On many systems, particularly Linux distributions, PostgreSQL logs are often stored in:

/var/log/postgresql/

That's it! It took quite a few steps, but now you have successfully installed and configured pgaudit in your PostgreSQL database.

A Better Foundation for Database Audit Logging 

Implementing audit logging with pgAudit is a significant step towards enhancing your database security and compliance posture.

If you want a high-performance but sturdy database as the foundation for your audit logging (delivered as a service), you can try Timescale Cloud for free for 30 days.

It combines all of your PostgreSQL faves—a wide ecosystem of tools and connectors, full SQL support, and battle-tested reliability—with a hard-working feature set that takes PostgreSQL to the next level for time series, events, analytics, and even AI. And with the pgAudit extension (among many others) available by default, it’s production-ready for even your most sensitive datasets.

On this page

    Try for free

    Start supercharging your PostgreSQL today.